<?php
function AFT_MakeTreeDB($vtur) {
	$time = time();
	global $vSettings;
    $vSettings = AFT_load('settings');

	list(, , , $sizeX, $sizeY) = explode(';', file_get_contents(F('playerinfo.txt')));
	$saveSettings = false;
	
	if (!isset($vSettings['size'])){
		$vSettings['size']=$sizeX;
		$vSettings['seed_x1']=0;
		$vSettings['seed_y1']=0;
		$vSettings['seed_x2']=45;
		$vSettings['seed_y2']=45;
		$saveSettings = true;
	}
	if (!$vSettings['preciousCoins']) {
		$vSettings['preciousCoins'] = 500;
		$saveSettings = true;
	}
	if (!$vSettings['preciousCocos']) {
		$vSettings['preciousCocos'] = 250;
		$saveSettings = true;
	}
	if (!$vSettings['preciousJade']) {
		$vSettings['preciousJade'] = 50;
		$saveSettings = true;
	}

	if ($vSettings['size'] !== $sizeX) {
	// farm size has changed
		$fark=$sizeX -  $vSettings['size'];
		$vSettings['seed_x1']=$vSettings['seed_x1']+ $fark;
		$vSettings['seed_y1']=$vSettings['seed_y1']+ $fark;
		$vSettings['seed_x2']=$vSettings['seed_x2']+ $fark;
		$vSettings['seed_y2']=$vSettings['seed_y2']+ $fark;
		$vSettings['size']=$sizeX;
		$saveSettings = true;

		$vSections = array();
		$vSections = AFT_load('sections');
		foreach ($vSections as &$sec) {
			$sec['x1']=$sec['x1']+$fark;
			$sec['x2']=$sec['x2']+$fark;
			$sec['y1']=$sec['y1']+$fark;
			$sec['y2']=$sec['y2']+$fark;
		}
		AFT_save($vSections, 'sections');
	}

	if ($saveSettings) AFT_save($vSettings, 'settings');

	$vOrchards = AFT_load('orchards');
	$objects  = array_merge(GetObjects('OrchardFeatureBuilding'),GetObjects('OrchardBuilding'),GetObjects('ArboretumBuilding'));
	//$vOrchards = array();
	foreach ($objects as $o) {
		foreach ($o['contents'] as $conts) {
			$vfind=false;
#			$vtid=Units_GetNameByCode($conts['itemCode']);
			for ($i=0; $i<count($vOrchards['oid']);$i++) {
				if ($vOrchards['oid'][$i]==$o['id'] && $vOrchards['tid'][$i]==$conts['itemCode']) {
					$vfind=true;
				}
			}
			if (!$vfind) { 	
				$vOrchards['oid'][]=$o['id'];	
				$vOrchards['tid'][]=$conts['itemCode'];
				$vOrchards['cnt'][]=0;
			}
		}
	}
	AFT_save($vOrchards, 'orchards');

	AddLog2("AllForTrees -> maketreedb (settings/sections/orchards) lap time ".(time()-$time))." secs";

	$vATrees=array();	
	$vATr=array();	
	$mastery_counters = @unserialize(@file_get_contents(F('cropmastery.txt')));
	$mastery_levels   = @unserialize(@file_get_contents(F('cropmasterycount.txt')));
	if ($vtur=='st' || $vtur=='all') {
		$vSTtrees=array();
		$vSTtrees  = AllForTrees_GetStorageTreeData();
	}
	if ($vtur=='seed' || $vtur=='all') $seeds =GetObjects('MysterySeedling');
	if ($vtur=='gb' || $vtur=='all') {
		$vGBtrees=array();
		$vGiftboxContent = AllForTrees_GetGiftboxContent();
		$vGBtrees        = $vGiftboxContent['tree'];
	}
	$vtcount=0;

	AddLog2("AllForTrees -> maketreedb (getobjects) lap time ".(time()-$time))." secs";
	
	$vGbTs=array();
	//treelist
	$vTrees = Units_GetByType("tree", true);
	foreach ($vTrees as $vTree) {
		if (!array_key_exists('masterymax',$vTree)) continue;

		$vATr = array();

		$vATr['name']=$vTree['name'];
		$vATr['code']=$vTree['code'];
		
		$vsdate = $vTree['limitedStart'];
		if (strlen($vsdate)==0) $vsdate='01/01/1900';
		$vdate = strtotime($vsdate);
		$vATr['date']=$vdate;

		$vATr['realname']=$vTree['realname'];
		$vATr['mascnt']=ceil($mastery_counters[$vTree['code']]);
		$vATr['masmax']=ceil($vTree['masterymax']);
		if ($vATr['masmax']==0) {
			$vATr['mastery']=0;
		} else {
			$vATr['mastery']=round(($vATr['mascnt'] / $vATr['masmax']), 3);
		}

		$stars = 0;
		if ($mastery_levels[$vTree['code']] > 0) {
			$stars = $mastery_levels[$vTree['code']] + 1;
		} elseif ($mastery_levels[$vTree['code']] == "0") {
			$stars = 1;
		}
		if ($vATr['mastery'] >= 1) $stars=3;
		$vATr['masstars']=$stars;		
		
		$vATr['coins']=intval($vTree['coinYield']);
		$vATr['cocos'] = 0;
		$vATr['jade'] = 0;
		$vATr[$vTree['harvestYield_0_type'] == "coconuts"?"cocos":$vTree['harvestYield_0_type']]=intval($vTree['harvestYield_0_yield']);
		$vATr['yieldtype']=	$vTree['harvestYield_0_type'];
		$vATr['iconurl']=$vTree['iconurl'];
		$vATr['action']='';
		$vATr['actioncnt']=0;
		$vATr['actionSeed']='';
		$vATr['actionSeedcnt']=0;
		$vATr['actionGB']='';
		$vATr['actionGBcnt']=0;
		$vATr['actionST']='';
		$vATr['actionSTcnt']=0;
		$vATr['actionBred']='tomast';
		$vATr['actionBredcnt']=0;
		$vATr['movetosec']=0;
		$vATr['movetoorc']=0;
		$vATr['cntSeed']=0;
		$vATr['cntGB']=0;
		$vATr['cntST']=0;
		$vATr['cnt']=0;

		if ($vSettings['autoSellMastered'] && $vATr['mastery'] >= 1) {
			if (! $vSettings['autoSellMasteredKeepPrecious']
				|| ($vATr['jade'] < $vSettings['preciousJade']
					&& $vATr['cocos'] < $vSettings['preciousCocos']
					&& $vATr['coins'] < $vSettings['preciousCoins'])) {
				$vATr['action'] = 'sell';
			}
		}
		
		
		$vATrees[$vATr['code']]=$vATr;
	}

	AddLog2("AllForTrees -> maketreedb (db) lap time ".(time()-$time))." secs";

	
	$Treeobjects = GetObjects('Tree');
	foreach ($Treeobjects as $o) {
		$u = Units_GetUnitByName($o['itemName']);
		$vATrees[$u['code']]['cnt']++;
	}

	foreach ($objects as $o) {
		if ($o['className']=='OrchardFeatureBuilding'
			|| $o['className']=='OrchardBuilding'
			|| $o['className']=='ArboretumBuilding'){
			foreach ($o['contents'] as $conts) {
				$vATrees[$conts['itemCode']]['cntOrc'] += intval($conts['numItem']);
			}
		}
	}

//seeds
	if ($vtur=='seed' || $vtur=='all') {
		foreach ($seeds as $s) {
			if (strlen($s['seedType'])) $vATrees[$s['seedType']]['cntSeed']++;
		}
	}

//inStorage******************************
	if ($vtur=='st' || $vtur=='all') {
		foreach ($vSTtrees as $t) {
			if (strlen($t['code'])) $vATrees[$t['code']]['cntST'] = intval($t["treeamount"]);
		}	
	}

//inGB***************************
	if ($vtur=='gb' || $vtur=='all') {
		foreach ($vGBtrees as $t) {
			if (strlen($t['code'])) $vATrees[$t['code']]['cntGB']++;
		}	
	}


// $vATrees now contains all dynamic data without saved settings
// now add settings from file
	$vAllTrees = AFT_load('alltrees');
	foreach ($vAllTrees as $code => $t) {
		foreach ($t as $k => $v) {
			$vATrees[$code][$k] = $v;
		}	
	}	

	AddLog2("AllForTrees -> maketreedb in ".(time()-$time)." secs");
	return $vATrees;
}
function AFT_TreeTable($vAllTrees) {
	if (!$vAllTrees) $vAllTrees = AFT_MakeTreeDB('all');
	$treetable = array();
	foreach ($vAllTrees as $t) {
		$treetable[$t['code']] = $t;
		$treetable[$t['name']] = $t;
	}
	return $treetable;

}
function AFT_TreeIndex($treedb) {
	$tdx = array();
	foreach ($treedb as $t) {
		$tdx[$t['code']] = $t;
		$tdx[$t['name']] = $t;
	}
	return $tdx;
}
function AllForTrees_Create_Map() {
	$SC = 4; // scale factor for drawing!
	list($level, $gold, $cash, $sizeX, $sizeY) = explode(';', file_get_contents(F('playerinfo.txt')));
	list($userId, $phpRevision, $token, $sequence, $flashSessionKey, $xp, $energy) = explode(';', file_get_contents(F('params.txt')));
	$vWorldtype       = file_get_contents(F('worldtype.txt'));
	$maxX             = $sizeX * $SC;
	$maxY             = $sizeY * $SC;
	$im               = @imagecreate($maxX, $maxY);
	$background_color = imagecolorallocate($im, 50, 120, 50);
	$red              = imagecolorallocate($im, 255, 0, 0);
	$green            = imagecolorallocate($im, 0, 255, 0);
	$blue             = imagecolorallocate($im, 0, 0, 255);
	$white            = imagecolorallocate($im, 255, 255, 255);
	$yellow           = imagecolorallocate($im, 255, 255, 0);
	$black            = imagecolorallocate($im, 0, 0, 0);
	$purple           = ImageColorAllocate($im, 153, 51, 255);
	$pink             = ImageColorAllocate($im, 255, 0, 126);
	$grey             = ImageColorAllocate($im, 192, 192, 192);
	$brown            = ImageColorAllocate($im, 150, 60, 60);
	$col_default = $grey;
	$col_orchardID = imagecolorallocate($im, 0, 200, 50 );
	$classCol = array(
		"OrchardBuilding" => imagecolorallocate($im, 0, 100, 30 ),
		"OrchardFeatureBuilding" => imagecolorallocate($im, 0, 100, 30 ),
		"OrchardConstructionBuilding" => imagecolorallocate($im, 0, 60, 10 ),
		"orchardsuper"  => imagecolorallocate($im, 0, 255, 80),
		"ArboretumBuilding" => imagecolorallocate($im, 20, 150, 30),
		"Plot" => imagecolorallocate($im, 102, 51, 0),
		"FixedTreasureConstructionBuilding" => $black,
		"CashGrowableBaby" => imagecolorallocate($im, 153, 0, 51),
		"Animal" => imagecolorallocate($im, 255, 0, 102),
		"Tree" => imagecolorallocate($im, 0, 80, 0),
		"LootableDecoration" => imagecolorallocate($im, 100, 80, 0),
		"FeatureBuilding" => imagecolorallocate($im, 102, 153, 153),
		"ConstructionBuilding" => imagecolorallocate($im, 102, 153, 153),
		"Garage" => imagecolorallocate($im, 102, 153, 153),
		"MarketStall" => imagecolorallocate($im, 102, 102, 153),
	);
	
	imagefilledrectangle($im, 0, 0, $maxX, $maxY, $background_color);
	$vSections = array();
	$vSections = AFT_load('sections');
	foreach ($vSections as $vsec) {
		$vtx = ($vsec['x2'] + 1) * $SC;
		$vbx = $vsec['x1'] * $SC;
		$vty = $maxY - ($vsec['y2'] + 1) * $SC;
		$vby = $maxY - $vsec['y1'] * $SC;
		imagefilledrectangle($im, $vbx, $vby, $vtx, $vty, $brown);
	}
	$vSettings = array();
	$vSettings = AFT_load('settings');
	$vtx       = ($vSettings['seed_x2'] + 1) * $SC;
	$vbx       = $vSettings['seed_x1'] * $SC;
	$vty       = $maxY - ($vSettings['seed_y2'] + 1) * $SC;
	$vby       = $maxY - $vSettings['seed_y1'] * $SC;
	imagefilledrectangle($im, $vbx, $vby, $vtx, $vty, $blue);
	$objects = @unserialize(file_get_contents(F('objects.txt')));
	

	foreach ($objects as $oID => $o) {
		$u = Units_GetUnitByName($o['itemName']);
		if (!isset($u['sizeX'])) {
			$u['sizeX'] = 1;
			$u['sizeY'] = 1;
		}
		if ($o['state'] == 'vertical') {
			$t          = $u['sizeX'];
			$u['sizeX'] = $u['sizeY'];
			$u['sizeY'] = $t;
		}
		$X1 = $o['position']['x'] * $SC;
		$Y1 = $maxY - $o['position']['y'] * $SC;
		$X2 = ($o['position']['x'] + $u['sizeX']) * $SC - 2;
		$Y2 = $maxY - ($o['position']['y'] + $u['sizeY']) * $SC + 2;
		
		$draw_col = $col_default;
		if (array_key_exists($o['className'],$classCol)) {
			$draw_col = $classCol[$o['className']];
		}
		
		imagefilledrectangle($im, $X1, $Y1, $X2, $Y2, $draw_col);
		
		if ($o['className'] == 'OrchardFeatureBuilding'
			|| $o['className'] == 'OrchardBuilding'
			|| $o['className'] == 'ArboretumBuilding') {
			imagestring($im, 1, $X1, $Y2, $o['id'], $col_orchardID);
		} elseif (! array_key_exists($o['className'],$classCol)) {
#			imagestring($im, 1, $X1, $Y2, $o['className'], $black);
		}
		
		
		
	}
	foreach ($vSections as $vsec) {
		$vbx = $vsec['x1'] * $SC;
		$vty = $maxY - ($vsec['y2'] + 1) * $SC;
		imagestring($im, 3, $vbx, $vty, $vsec['name'] ?: $vsec['id'], $white);
	}
	$vbx = $vSettings['seed_x1'] * $SC;
	$vty = $maxY - ($vSettings['seed_y2'] + 1) * $SC;
	imagestring($im, 3, $vbx, $vty, 'seeds', $white);
	$map_image = "plugins/AllForTrees/data/" . $vWorldtype . $userId . "_Map.png";
	imagepng($im, $map_image);
	imagedestroy($im);
}
function crmultiple($x1,$x2,$y1,$y2,$w,$h,$sx,$sy,$id,$ord) {
	$alanlar=array();
	$w;
	$h;

	$k=floor(($x2-$x1) / ($w+$sx));
	$l=floor(($y2-$y1) / ($h+$sy));
	if ((($k + 1)*($w+$sx) -$sx) < ($x2-$x1)) $k++;
	if ((($l + 1)*($h+$sy) -$sy) < ($y2-$y1)) $l++;

	for ($i=0; $i<$k; $i++){ 
		for ($j=0; $j<$l; $j++) {
			$vsec=array();
			$vsec['id']   = $id;
			$vsec['order'] = $ord;
			$vsec['x1'] = $i*$w + $i*$sx + $x1;
			$vsec['y1'] = $j*$h + $j*$sy + $y1;	
			$vsec['x2'] = $vsec['x1'] + $w-1;
			$vsec['y2'] = $vsec['y1'] + $h-1;
			$alanlar[] = $vsec;
			$id++;
		}
	}
	return $alanlar;
}
function AFT_checkCellar() {
	$vinventory=@unserialize(file_get_contents(F('featurecredits.txt')));
	$vstorage=@unserialize(file_get_contents(F('instorage.txt')));
	$vtot=0;
	if (is_array($vinventory)) $vtot=intval($vinventory['InventoryCellar']['received']);

	$vcap=0;
	foreach ($vstorage as $storekey => $storenumItems) {
		if ($storenumItems > 0) $vcap=$vcap+$storenumItems;
	}

	$vcap=$vtot -$vcap;
	if ($vcap<0) $vcap=0;
	return $vcap;
}
function AFT_AMFSTRtoFarm_old($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);
	$j           = 0;
	global $vCnt63000;
	if ($vCnt63000 < 63000)
		$vCnt63000 = 63000;
	$Sspeed                        = 8;

/*	$amf                           = new AMFObject("");
	$amf->_bodys[0]                = new MessageBody();
	$amf->_bodys[0]->targetURI     = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->responseURI   = '/1/onStatus';
	$amf->_bodys[0]->responseIndex = '/1';
	$amf->_bodys[0]->_value[0]     = GetAMFHeaders();
	$amf->_bodys[0]->_value[2]     = 0;
*/
    $amf = CreateRequestAMF('place', 'WorldService.performAction');


	while ($j < $vcnt) {
		$sNumAction = 0;
		$resstr='';
		while ($sNumAction < $Sspeed && $j < $vcnt) {
		
			AddLog2("Try to place {$vTDB[$j]['itemName']} to {$vTDB[$j]['position']['x']}/{$vTDB[$j]['position']['y']} from {$vTDB[$j]['strid']} ..");
		
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id']                     = $vCnt63000++;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted']                = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName']               = $vTDB[$j]['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId']                 = -1;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction']              = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x']          = $vTDB[$j]['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y']          = $vTDB[$j]['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z']          = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime']              = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state']                  = $vTDB[$j]['state'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className']              = $vTDB[$j]['className'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isGift']              = $vTDB[$j]['isGift'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isStorageWithdrawal'] = $vTDB[$j]['strid'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energyCost']          = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energySource']        = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energyMetadata']      = '';
			$resstr=$resstr. ' ['.$vTDB[$j]['position']['x'].'/'.$vTDB[$j]['position']['y'].'] '.$vTDB[$j]['itemName'].',';
			$sNumAction++;
			$j++;
		}
		//print_r($amf);
		$res = RequestAMF($amf);
		AddLog2("AllForTrees -> moving to farm $resstr .. $res");

#		$vtemplist = AllForTrees_CheckAMF2ResponsePlace($amf2,$vtemplist,$j);
		unset($amf->_bodys[0]->_value[1]);
	}
	return $vtemplist;
}
function AFT_AMFSTRtoFarm($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);
	foreach ($vTDB as $j => $vt) {
		// AddLog2("Place {$vt['itemName']} ...");
// Mithelen - Check return status. If failed stop trying to place
		$res = GB_PlaceItem($vt['itemName'],$vt['position'],$j,$vcnt,$vt['strid']);

		if ($res != "OK") break;
	}
}
function AFT_AMFSTRtoFarm_NotWorking($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);
	global $vCnt63000, $vWorldtype;
	$state = 'static';
	$wi = Parser_GetWorldInfo($vWorldtype);
	$vWorldtype = $wi[2];

	$amfi = 0;
	$sspeed = 7;
	
	foreach ($vTDB as $j => $vt) {
		AddLog2("Place {$vt['itemName']} ...");

		
		// GB_PlaceItem($vt['itemName'],$vt['position'],$j,$vcnt,$vt['strid']);
		$loc=$vt['position'];
		$unit = Units_GetUnitByName($vt['itemName'], true);
		$state = 'bare';
		$isGift = false;

		if($unit['className'] == 'rotateableDecoration') $state = 'horizontal';

		if ($amfi == 0) $amf = CreateRequestAMF('place', 'WorldService.performAction');
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['itemName']               = $unit['name'];
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['direction']              = 1; // 0
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['state']                  = $state;
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['deleted']                = false;
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['id']                     = $vCnt63000++;
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['className']              = $unit['className'];
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['tempId']                 = -1;
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['z']          = 0;
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['x']          = $loc['x'];
		$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['y']          = $loc['y'];
		$amf->_bodys[0]->_value[1][$amfi]['sequence']                            = GetSequense();
		$amf->_bodys[0]->_value[1][$amfi]['sequenceID'] = $GLOBALS['sequence_id'];

		$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isStorageWithdrawal'] = $vt['strid'];
		$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['giftMetadataIndex']   = -1;
		$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isInventoryWithdrawal']= false;
		$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['expansionLevel']       = 0;
		$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isGift']              = $isGift;

		$amfi++;
		
		if ($amfi > $sspeed) {
			$res = RequestAMF($amf);
			if($res == 'OK') AddLog2("AllForTrees -> Place [".($i+1)."/$tot] $unit[realname] on [$loc[x]/$loc[y]] from $str >>> $res");
				else AddLog2("AllForTrees -> ERROR [$amfi] placing [".($i+1)."/$tot] $unit[realname] on [$loc[x]/$loc[y]] from $str >>> $res");
			$amfi = 0;
		}



					


	}
}
function GB_PlaceItem($items = '', $loc = array(), $i, $tot,$str=-1) {
   
	global $vCnt63000, $vWorldtype;
	$state = 'static';
	$wi = Parser_GetWorldInfo($vWorldtype);
	$vWorldtype = $wi[2];
	$unit = Units_GetUnitByName($items, true);
	if($unit['type'] == 'animal')$state = 'bare';
	// if($unit['type'] == 'tree')$state = 'bare';
	$isGift = true;

	if ($str > 0) {
		$state = 'bare';
		$isGift = false;
	}
	if($unit['className'] == 'rotateableDecoration')$state = 'horizontal';


	$amfi = 0;
	$amf = CreateRequestAMF('place', 'WorldService.performAction');
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['itemName']               = $unit['name'];
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['direction']              = 1; // 0
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['state']                  = $state;
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['deleted']                = false;
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['id']                     = $vCnt63000++;
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['className']              = $unit['className'];
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['tempId']                 = -1;
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['z']          = 0;
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['x']          = $loc['x'];
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['position']['y']          = $loc['y'];

	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isStorageWithdrawal'] = $str;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['giftMetadataIndex']   = -1;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isInventoryWithdrawal']= false;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['expansionLevel']       = 0;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['isGift']              = $isGift;


/*
if ($str > 0) {
	$amf->_bodys[0]->_value[1][$amfi]['params'][1]['plantTime']              = 0;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['energyCost']          = 0;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['energySource']        = 0;
	$amf->_bodys[0]->_value[1][$amfi]['params'][2][0]['energyMetadata']      = '';
}
	*/	
	$amfi++;

	$res = RequestAMF($amf);
	if($res == 'OK') AddLog2("AllForTrees -> Place [".($i+1)."/$tot] $unit[realname] on [$loc[x]/$loc[y]] from $str >>> $res");
		else AddLog2("AllForTrees -> ERROR [$amfi] placing [".($i+1)."/$tot] $unit[realname] on [$loc[x]/$loc[y]] from $str >>> $res");

// Mithelen - Return status
	return $res;
} 
function AFT_AMFFarmtoStr($vTDB) {
	global $need_reload;
	$need_reload               = true;
	$vcnt                      = count($vTDB);
	$Sspeed                    = 8;
	$i                         = 0;
	$amf                       = new AMFObject("");
	$amf->_bodys[0]            = new MessageBody();
	$amf->_bodys[0]->targetURI = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->_value[0] = GetAMFHeaders();
	$amf->_bodys[0]->_value[2] = 0;

	while ($i < $vcnt) {
	$sNumAction = 0;
	$resstr='';
		while ($sNumAction < $Sspeed && $i < $vcnt) {
			$amf->_bodys[0]->_value[1][$sNumAction]['sequence']                         = GetSequense();
			$amf->_bodys[0]->_value[1][$sNumAction]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$sNumAction]['functionName']                     = 'WorldService.performAction';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][0]                        = "store";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]                        = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id']                  = $vTDB[$i]['orchard']['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted']             = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId']              = -1;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state']               = $vTDB[$i]['orchard']['state'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName']            = $vTDB[$i]['orchard']['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']            = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x']       = $vTDB[$i]['orchard']['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y']       = $vTDB[$i]['orchard']['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z']       = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className']           = $vTDB[$i]['orchard']['className'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime']           = $vTDB[$i]['orchard']['plantTime'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['buildTime']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['components']          = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['contents']            = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2]                        = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]                     = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedClassName']  = "Tree";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemName']   = $vTDB[$i]['name'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['metadata']         = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemCode']   = $vTDB[$i]['code'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['resource']         = $vTDB[$i]['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isFull']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isGift']           = false;
			$resstr=$resstr. ' '. $vTDB[$i]['realname'].',';
			$sNumAction++;
			$i++;
		}
		AddLog2("AllForTrees -> Moving to {$vTDB[$i]['orchard']['itemName']} #{$vTDB[$i]['orchard']['id']}: $resstr");
		$res = RequestAMF($amf);
		AddLog2($res);
		unset($amf->_bodys[0]->_value[1]);
	}
}
function AFT_AMFSell($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);
	$j           = 0;
	$Sspeed      = 8;
	$amf                           = new AMFObject("");
	$amf->_bodys[0]                = new MessageBody();
	$amf->_bodys[0]->targetURI     = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->responseURI   = '/1/onStatus';
	$amf->_bodys[0]->responseIndex = '/1';
	$amf->_bodys[0]->_value[0]     = GetAMFHeaders();
	$amf->_bodys[0]->_value[2]     = 0;	

	
/*	maybe use
		$amf = CreateRequestAMF('', 'UserService.initUser');
		$amf->_bodys[0]->_value[1][0]['params'][0] = "";
		$amf->_bodys[0]->_value[1][0]['params'][1] = -1;
		$amf->_bodys[0]->_value[1][0]['params'][2] = true;

		$amf2=RequestAMFIntern($amf);
		$res=CheckAMF2Response($amf2);	instead
*/

	
	while ($j < $vcnt) {
		$sNumAction = 0;
		$resstr='';
		while ($sNumAction < $Sspeed && $j < $vcnt) {
			$amf->_bodys[0]->_value[1][$sNumAction]['functionName']    = "WorldService.performAction";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][0]  = 'sell';
			$amf->_bodys[0]->_value[1][$sNumAction]['sequence']   = GetSequense();
			$amf->_bodys[0]->_value[1][$sNumAction]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]   = array();	
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['components']    = $vTDB[$j]['components'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName']      = $vTDB[$j]['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className']     = $vTDB[$j]['className'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id']            = $vTDB[$j]['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state']         = $vTDB[$j]['state'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime']     = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted']       = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['buildTime']     = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId']        = 'NaN';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction']     = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['contents']      = $vTDB[$j]['contents'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x'] = $vTDB[$j]['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y'] = $vTDB[$j]['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z'] = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2]                  = '';
			$resstr=$resstr. ' ('.$vTDB[$j]['position']['x'].'/'.$vTDB[$j]['position']['y'].') '.$vTDB[$j]['itemName'].',';
			$sNumAction++;
			$j++;
		}	
	$res = RequestAMF($amf);
	unset($amf->_bodys[0]->_value[1]);
		AddLog2("AllForTrees -> Selling: $resstr");
		AddLog2("Result: $res");
	}	
}
function AFT_AMFWater($vTDB) {
	global $need_reload,$sequence_id;
	$vcnt=count($vTDB);

	$amf                       = new AMFObject("");
	$amf->_bodys[0]            = new MessageBody();
	$amf->_bodys[0]->targetURI = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->_value[0] = GetAMFHeaders();
	$amf->_bodys[0]->_value[2] = 0;
	$j=0;
	foreach($vTDB as $bld) {
		$i = 0;
		while ($i< $bld['watercnt']) {
			$amf->_bodys[0]->_value[1][$i]['functionName']                     = "WorldService.performAction";
			$amf->_bodys[0]->_value[1][$i]['params'][0]                        = "store";
			$amf->_bodys[0]->_value[1][$i]['sequence']                         = GetSequense();
			$amf->_bodys[0]->_value[1][$i]['sequenceID'] = $GLOBALS['sequence_id'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['plantTime']           = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['itemName']            = 'mysteryseedling';
			$amf->_bodys[0]->_value[1][$i]['params'][1]['className']           = 'MysterySeedling';
			$amf->_bodys[0]->_value[1][$i]['params'][1]['contents']            = array();
			$amf->_bodys[0]->_value[1][$i]['params'][1]['state']               = 'construction';
			$amf->_bodys[0]->_value[1][$i]['params'][1]['deleted']             = false;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['id']                  = $bld['id'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['direction']           = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['tempId']              = "NaN";
			$amf->_bodys[0]->_value[1][$i]['params'][1]['components']          = null;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']            = null;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['x']       = $bld['position']['x'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['y']       = $bld['position']['y'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['z']       = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['buildTime']           = 0;
			
			$amf->_bodys[0]->_value[1][$i]['params'][2]                        = array();
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['resource']         = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedItemName']   = 'wateringcan';
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedItemCode']   = 'wO';
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['isGift']           = true;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedClassName']  = 'BuildingPart';
			
			$i++;
		}
		$j++;
		$res = RequestAMF($amf);
		if ($res === 'OK') {
			$need_reload = true;
		}
		Addlog2("AllForTrees -> Watering seedling $j of {$vcnt} with $i cans: Result: $res");
	}
}
function AFT_AMFStore($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);	
	$amf = new AMFObject("");
	$amf->_bodys[0] = new MessageBody();

	$amf->_bodys[0]->targetURI = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->responseURI = '/1/onStatus';
	$amf->_bodys[0]->responseIndex = '/1';

	$amf->_bodys[0]->_value[0] = GetAMFHeaders();
	$amf->_bodys[0]->_value[2] = 0;
	$i = 0;
	$Sspeed=8;
	while ($i < $vcnt) {
		$sNumAction = 0;
		$resstr='';
		while ($sNumAction < $Sspeed && $i < $vcnt) {
			$amf->_bodys[0]->_value[1][$sNumAction]['functionName'] 	= "WorldService.performAction";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][0] 	= 'store';
			$amf->_bodys[0]->_value[1][$sNumAction]['sequence'] 		= GetSequense();
			$amf->_bodys[0]->_value[1][$sNumAction]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]                  = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className'] = $vTDB[$i]['className'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName'] = $vTDB[$i]['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted'] = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId'] = -1;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id'] = $vTDB[$i]['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state'] = $vTDB[$i]['state'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime'] = $vTDB[$i]['plantTime'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction'] = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['components'] = '';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x'] = $vTDB[$i]['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y'] = $vTDB[$i]['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z'] = 0;
			
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2]                  = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]                  = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['origin']     = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isGift']     = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['resource']   = $vTDB[$i]['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['target']     = $vTDB[$i]['strid'];	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemName']     = $vTDB[$i]['itemName'];	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedClassName']     = 'Tree';	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemCode']     = $vTDB[$i]['code'];	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['code']     = $vTDB[$i]['code'];	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isStorageWithdrawal']     = 0;	  
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['metadata']     = null;	  
			$resstr=$resstr. ' '. $vTDB[$i]['itemName'].',';
			$i++;
			$sNumAction++;
		}
		$res = RequestAMF($amf);
		addlog2("AllForTrees -> Storing ".$resstr.". Result: ".$res);
	}
}
function AFT_AMFStoreToStore($vTDB) {
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vTDB);
	global $vCnt63000;
	if ($vCnt63000 < 63000)
		$vCnt63000 = 63000;	

			$amf = new AMFObject("");
			$amf->_bodys[0] = new MessageBody();

			$amf->_bodys[0]->targetURI = 'FlashService.dispatchBatch';
			$amf->_bodys[0]->responseURI = '/1/onStatus';
			$amf->_bodys[0]->responseIndex = '/1';

			$amf->_bodys[0]->_value[0] = GetAMFHeaders();
			$amf->_bodys[0]->_value[2] = 0;
			$i = 0;

		foreach($vTDB as $vitem) {

			$amf->_bodys[0]->_value[1][$i]['functionName'] 	= "WorldService.performAction";
			$amf->_bodys[0]->_value[1][$i]['params'][0] 	= 'store';
			$amf->_bodys[0]->_value[1][$i]['sequence'] 		= GetSequense();
			$amf->_bodys[0]->_value[1][$i]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$i]['params'][1]                  = array();
			$amf->_bodys[0]->_value[1][$i]['params'][1]['className'] = $vitem['className'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['itemName'] = $vitem['itemName'];
			$amf->_bodys[0]->_value[1][$i]['params'][1]['deleted'] = false;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['tempId'] = -1;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['id'] = $vCnt63000++;
			$amf->_bodys[0]->_value[1][$i]['params'][1]['state'] = 'static';
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['plantTime'] = $vitem['plantTime'];
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['direction'] = 0;
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['components'] = '';
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['x'] = $vitem['position']['x'];
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['y'] = $vitem['position']['y'];
//			$amf->_bodys[0]->_value[1][$i]['params'][1]['position']['z'] = 0;
			
			$amf->_bodys[0]->_value[1][$i]['params'][2]                  = array();
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]                  = array();
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['origin']     = $vitem['strid2'];
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['isGift']     = false;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['resource']   = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['target']     = $vitem['strid'];	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedItemName']     = $vitem['itemName'];	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedClassName']     = 'Tree';	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['storedItemCode']     = $vitem['code'];	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['code']     = $vitem['code'];	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['isStorageWithdrawal']     = $vitem['strid2'];	  
			$amf->_bodys[0]->_value[1][$i]['params'][2][0]['metadata']     = null;	  
			 $i++;
}
						$res = RequestAMF($amf);


}
function AFT_AMFChangeFarm($vSettingsWorldtype,$vWorldtype,$vSettingsWorldfreez) {
	$amf = CreateRequestAMF('', 'UserService.saveOptions');
	$amf->_bodys[0]->_value[1][0]['params'][0]['shouldFreezeFarm'] = $vSettingsWorldfreez=='freez'?true:false; # false continue farm / true freez farm
	$amf->_bodys[0]->_value[1][0]['params'][0]['sfxDisabled'] = true;
	$amf->_bodys[0]->_value[1][0]['params'][0]['musicDisabled'] = true;
	$amf->_bodys[0]->_value[1][0]['params'][0]['graphicsLowQuality'] = true;
	$amf2 = RequestAMFIntern($amf);
	$res=CheckAMF2Response($amf2);
	if ($res == 'OK') {
		AddLog2("DoInit: FreezFarm successful changed to $vSettingsWorldfreez");
	} else {
		AddLog2("DoInit: FreezFarm error $res changing to $vSettingsWorldfreez");
	}
	$amf = CreateRequestAMF('', 'WorldService.loadOwnWorld');
	$amf->_bodys[0]->_value[1][0]['params'][0] = $vSettingsWorldtype;
	$amf->_bodys[0]->_value[1][0]['params'][1] = true;
	$amf->_bodys[0]->_value[1][0]['params'][2] = $vSettingsWorldfreez=='freez'?true:false; # false continue farm / true freez farm
	$amf2 = RequestAMFIntern($amf);
	$res=CheckAMF2Response($amf2);
	if ($res == 'OK') {
		AddLog2("DoInit: SwitchFarm successful switched to $vSettingsWorldtype");
	} else {
		AddLog2("DoInit: SwitchFarm error $res switching to $vSettingsWorldtype");
	}
	DoInit();
}
function AllForTrees_ToStorage() {
	AddLog2("AllForTrees [Storage storing]");

	global $need_reload;
	global $vAllTrees;
	global $storageID;
	
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	

	$vSettingsWorldtype=@file_get_contents(F('worldtype.txt'));

	$storeme = array();
	$storecnt = 0;
	foreach ($vAllTrees as $t) {
		if ($t['actionST'] == 'store') {
			$num = $t['cnt'] - intval($t['actionSTcnt']);
			if ($num < 0) $num = 0;
			if ($num) {
				$t['storeCNT'] = $num;
				$storeme[]=$t;
				$storecnt += $num;
			}
		}
	}
	if ($storecnt) {
		AddLog2("AllForTrees -> Storing $storecnt trees to {$storageID[$vSettingsWorldtype]} ...");
	} else {
		return;
	}


	$objects = GetObjects('Tree');

	$vtb = array();
	foreach ($storeme as $st) {
		$cnt = $st['storeCNT'];
		foreach ($objects as $oID => $o) {
			if ($cnt <= 0) break;
			if ($o['itemName'] == $st['name']) {
				$o['code']=$st['code'];
				$o['strid']=$storageID[$vSettingsWorldtype];
				$vtd[]=$o;
				$cnt --;
			}
		}
	}
	
	if ($vtd) {
		AFT_AMFStore($vtd);
		$need_reload == true;
	}
}
function AllForTrees_Transport() {
	AddLog2("AllForTrees [Transporting]");

	global $need_reload;
	global $vAllTrees;

	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	
	$vTDBhm=array();
	$vTDBen=array();
	$vTDBfi=array();
	$vTDBww=array();
	$vTDBhi=array();
	$objects   =GetObjects('Tree');
	foreach ($vAllTrees as $vTree) {
		if ($vTree['actiontransp'] =='farm') {
			$cntitm=$vTree['cnt'] - intval($vTree['actiontranspcnt']);
			if ($cntitm > 0)
				foreach ($objects as $oID => $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$o['code']=$vTree['code'];
						$vTDBhm[]=$o;
						$cntitm--;
					}
				}
		} elseif ($vTree['actiontransp'] =='england') {
			$cntitm=$vTree['cnt'] - intval($vTree['actiontranspcnt']);
			if ($cntitm > 0)
				foreach ($objects as $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$o['code']=$vTree['code'];
						$vTDBen[]=$o;
						$cntitm--;
					}
				}
		} elseif ($vTree['actiontransp'] =='fisherman') {
		$cntitm=$vTree['cnt'] - intval($vTree['actiontranspcnt']);
		if ($cntitm > 0)
				foreach ($objects as $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$o['code']=$vTree['code'];
						$vTDBfi[]=$o;
						$cntitm--;
					}
				}
		} elseif ($vTree['actiontransp'] =='winterwonderland') {
		$cntitm=$vTree['cnt'] - intval($vTree['actiontranspcnt']);
		if ($cntitm > 0)
				foreach ($objects as $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$o['code']=$vTree['code'];
						$vTDBww[]=$o;
						$cntitm--;
					}
				}
		} elseif ($vTree['actiontransp'] =='hawaii') {
		$cntitm=$vTree['cnt'] - intval($vTree['actiontranspcnt']);
		if ($cntitm > 0)
				foreach ($objects as $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$o['code']=$vTree['code'];
						$vTDBhi[]=$o;
						$cntitm--;
					}
				}
		}
	}
	
	
	if (count($vTDBhm)>0) {
				AddLog2('AllForTrees -> transporting '.count($vTDBhm).' trees to home farm...');
				AllForTrees_Transport2('farm',$vTDBhm);
				}		
	if (count($vTDBen)>0) {
				AddLog2('AllForTrees -> transporting '.count($vTDBen).' trees to england...');
				AllForTrees_Transport2('england',$vTDBen);
				}		
	if (count($vTDBfi)>0) {
				AddLog2('AllForTrees -> transporting '.count($vTDBfi).' trees to fisherman...');
				AllForTrees_Transport2('fisherman',$vTDBfi);
				}		
	if (count($vTDBww)>0) {
				AddLog2('AllForTrees -> transporting '.count($vTDBww).' trees to winterwonderland...');
				AllForTrees_Transport2('winterwonderland',$vTDBww);
				}		
	if (count($vTDBhi)>0) {
				AddLog2('AllForTrees -> transporting '.count($vTDBhi).' trees to hawaii...');
				AllForTrees_Transport2('hawaii',$vTDBhi);
				}		

}
function AllForTrees_Transport2($vtarget,$vTDB) {
	$vSettingsWorldfreez=@file_get_contents(F('worldfreez.txt'));
	if(strlen($vSettingsWorldfreez)==0) $vSettingsWorldfreez='continue';
	$vSettingsWorldtype=@file_get_contents(F('worldtype.txt'));

	switch ($vSettingsWorldtype) {
		case 'farm':
			$iTarget = -2;
			break;
		case 'england':
			$iTarget = -8;
			break;
		case 'fisherman':
			$iTarget = -9;
			break;
		case 'winterwonderland':
			$iTarget = -10;
			break;
		case 'hawaii':
			$iTarget = -11;
			break;
	}

	$vcap=AFT_checkCellar();
	$vcnt        = count($vTDB);
	$i           = 0;
	$vTemp=array();
	while ($i < $vcnt) {
	AddLog2('AllForTrees -> Transport ['.$i.'/'.$vcnt.'] trees');
	$sNumAction = 0;
	unset($vTemp);
		while ($sNumAction < $vcap && $i < $vcnt) {
			$vTDB[$i]['strid']=$iTarget;
			$vTDB[$i]['isGift']=false;
			$vTemp[]=$vTDB[$i];
			$sNumAction++;
			$i++;
		}
		

		//store
		AFT_AMFStore($vTemp);
		//change farm
		AFT_AMFChangeFarm($vtarget,$vSettingsWorldtype,$vSettingsWorldfreez);
		//AFT_AMFStoreToStore($vTemp);
		//place
		//find free places
		for ($j=0; $j<count($vTemp);$j++) {
		 $nlocation=AllForTrees_GetFreeLocation($j);
		 //$nlocation=Parser_Find_Location($vTemp[$j]['code']);
		 $vTemp[$j]['position']['x']=$nlocation['x'];
		 $vTemp[$j]['position']['y']=$nlocation['y'];
		 }
		AFT_AMFSTRtoFarm($vTemp);
		//change farm
		AFT_AMFChangeFarm($vSettingsWorldtype,$vtarget,$vSettingsWorldfreez);
		
	}	
}	

function AllForTrees_GetFreeLocation($num) {
	global $vMap;
	list(, , , $sizeX, $sizeY) = explode(';', file_get_contents(F('playerinfo.txt')));
	$i = 0;
	for ($x = 0; $x < $sizeX; $x++) {
		for ($y = 0; $y < $sizeY; $y++) {
			if ($vMap[$x][$y] == true) {
				if ($i >= $num) {
					$vLocation['x'] = $x;
					$vLocation['y'] = $y;
					return ($vLocation);
				}
				$i++;
			}
		}
	}
}
function AllForTrees_PlaceSeedlings() {
	AddLog2("AllForTrees [Seedlings place]");

	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$need_reload = false;
	} //$need_reload == true	
	list(, , , $sizeX, $sizeY) = explode(';', file_get_contents(F('playerinfo.txt')));
	global $vMap;
	$vSettings = array();
	$vTDB=array();
	$vItem=array();
		
	$vSettings = AFT_load('settings');
	if ($vSettings['autoPlaceSeedlings'] || $vSettings['Seedplacecnt'] > 0) {
		$vmscnt = intval(AllForTrees__HowmanyinGB('mysteryseedling'));
		AddLog2("AllForTrees -> $vmscnt Mystery Seedling(s) in giftbox");
	}
	
	if ($vSettings['autoPlaceSeedlings']) {
		$vSettings['Seedplacecnt'] = $vmscnt - $vSettings['autoPlaceSeedlingsKeep'];
	}
	if (($vSettings['Seedplacecnt'] > 0) && ($vmscnt > 0)) {
		$place = $vSettings['Seedplacecnt'] > $vmscnt ? $vmscnt : $vSettings['Seedplacecnt'];
		AddLog2("AllForTrees -> placing $place seedlings from giftbox...");
		$foundplace=0;
		for ($x = $vSettings['seed_x2']; $x >= $vSettings['seed_x1']; $x--) {
			for ($y = $vSettings['seed_y2']; $y >= $vSettings['seed_y1']; $y--) {
				if ($vMap[$x][$y] == true) {
					$foundplace++;
					if (($vSettings['Seedplacecnt'] > 0) && ($vmscnt > 0)) {
						unset($vItem);
						$vItem['itemName']='mysteryseedling';
						$vItem['position']['x']=$x;
						$vItem['position']['y']=$y;
						$vItem['state']='static';
						$vItem['isGift']='true';
						$vItem['className']='MysterySeedling';
						$vItem['strid']=-1;
						$vTDB[]=$vItem;
						//Parser_Place_From_Giftbox($vCode, $vLocation);
						$vSettings['Seedplacecnt']--;
						$vmscnt--;
					}
				}
			}
		}
		if ($foundplace == 0) AddLog2("No space found for Mystery Seedling!");
	}
	if (count($vTDB)>0) {
		AFT_save($vSettings, 'settings');
		AddLog2('AllForTrees -> placing '.count($vTDB).' Mystery Seedlings...');
		AddLog('AllForTrees -> placing '.count($vTDB).' Mystery Seedlings...');
		AFT_AMFSTRtoFarm($vTDB);
	}
}
function AllForTrees_SeedsSell() {
	AddLog2("AllForTrees [Seedling sell]");

	global $need_reload;
	global $vAllTrees;

	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	
	$vSettings = array();
	$vSettings = AFT_load('settings');
	$vTDB=array();
	
	$buildings = GetObjects('MysterySeedling');

	foreach ($buildings as $vItem) {
		if ($t = $vAllTrees[$vItem['seedType']]) {
		AddLog2("seedling {$t['realname']} action: {$t['actionSeed']}, mastery: {$t['mastery']}");
			if ((
				($t['actionSeed'] == 'sell' && $t['actionSeedcnt'] != 0)
				|| ($t['mastery'] >= 1 && $vSettings['seedMasteredAction'] == 'sell' && (! $t['actionSeed'] || $t['actionSeed']=='select'))
				|| ($t['mastery'] < 1 && $vSettings['seedUnmasteredAction'] == 'sell' && (! $t['actionSeed'] || $t['actionSeed']=='select'))
			)
			&& $t['cntSeed'] > 0) {
				$vTDB[]=$vItem;
				unset($buildings[$vItem]);
				if ($t['actionSeedcnt'] > 0 ) $t['actionSeedcnt']--;
				$t['cntSeed']--;
			}
		}
	}
	
	if (($vSettings['Seedunk'] == 'sell') && ($vSettings['Seedunkcnt'] != 0) && (count($buildings) > 0)) {
		foreach ($buildings as $vItem) {
			if (Units_GetNameByCode($vItem['seedType']) == '' && ($vSettings['Seedunkcnt'] > 0) && (count($buildings) > 0)) {
				$vTDB[]=$vItem;
				unset($buildings[$vItem]);
				if ($vSettings['Seedunkcnt']>0) $vSettings['Seedunkcnt']--;
			}
		}
	}
	if (count($vTDB)>0) {
		AFT_save($vSettings, 'settings');
		AFT_save($vAllTrees, 'alltrees');
		AddLog2('AllForTrees -> selling '.count($vTDB).' Mystery Seedlings...');
		AFT_AMFsell($vTDB);
	}
}
function AllForTrees_Watering() {
	AddLog2("AllForTrees [Seedling watering]");
	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	
	$vSettings       = array();
	$vSettings       = AFT_load('settings');
	$buildings       = GetObjects('MysterySeedling');
	$vGiftboxContent = AllForTrees_GetGiftboxContent();
	$vAllGB          = $vGiftboxContent['building'];
	$vAllWaters      = array();
	$vTDB=array();
	foreach ($vAllGB as $vagb) {
		if ($vagb['name'] == 'wateringcan') {
			$vAllWaters[] = $vagb;
		}
	}
	
	if ($vSettings['Seedwater'] == 8) {
		$vmaxwater = 8;
	} elseif ($vSettings['Seedwater'] == 7){
		$vmaxwater = 7;
	} else {
		$vmaxwater = 3;
	}

	$totalwcount = count($vAllWaters);
	$totalgbwcount = $totalwcount;
	if ($vSettings['keepWateringcans'] > 0) $totalwcount -= $vSettings['keepWateringcans'];
	if ($totalwcount < 0) $totalwcount = 0;
	
	$treecount = floor($totalwcount/$vmaxwater);
	addLog2("AllForTrees -> ({$totalgbwcount} in GB) {$totalwcount} watering cans usable (for {$treecount} trees using {$vmaxwater} cans)");

	
	// foreach ($vAllTrees as &$t) {
		// if ($t['actionSeed'] == 'water' ) {
			// foreach ($buildings as $vItem) {
				// $wcnt=intval($vItem['contents'][0]['numItem']);
				// if ($t['code'] == $vItem['seedType'] && 
					// $t['actionSeedcnt'] != 0 &&
					// $t['cntSeed'] > 0 &&
					// $wcnt < $vmaxwater &&
					// $totalwcount >= ($vmaxwater - $wcnt)
					// ) {
					// $vItem['watercnt']=$vmaxwater - $wcnt;
					// $vTDB[]=$vItem;
					// unset($vItem['watercnt']);
					// unset($buildings[$vItem]);
					// $totalwcount = $totalwcount - ($vmaxwater - $wcnt);
					// if ($t['actionSeedcnt'] > 0 ) $t['actionSeedcnt']--;
					// $t['cntSeed']--;
				// }
			// }
		// }
	// }


	foreach ($buildings as $vItem) {
		$t = $vAllTrees[$vItem['seedType']];
		if ($vItem['seedType'] && $t) {
			$wcnt=intval($vItem['contents'][0]['numItem']);

			if ((($t['actionSeedcnt'] != 0 && $t['actionSeed'] == 'water')
						|| ($t['mastery'] >= 1 && $vSettings['seedMasteredAction'] == 'water'  && ! $t['actionSeed'])
						|| ($t['mastery'] < 1 && $vSettings['seedUnmasteredAction'] == 'water'  && ! $t['actionSeed'])
					)
					&& $t['cntSeed'] > 0
					&& $wcnt < $vmaxwater
					&& $totalwcount >= ($vmaxwater - $wcnt)
				) {
				$vItem['watercnt']=$vmaxwater - $wcnt;
				$vTDB[]=$vItem;
				unset($vItem['watercnt']);
				unset($buildings[$vItem]);
				$totalwcount = $totalwcount - ($vmaxwater - $wcnt);
				if ($t['actionSeedcnt'] > 0 ) $t['actionSeedcnt']--;
				$t['cntSeed']--;
			}
		}
	}
	
	if (($vSettings['Seedunk'] == 'water') && ($vSettings['Seedunkcnt'] != 0) && (count($buildings) > 0)) {
		foreach ($buildings as $vItem) {
			$wcnt=intval($vItem['contents'][0]['numItem']);
			if (Units_GetNameByCode($vItem['seedType']) == '' && 
				$vSettings['Seedunkcnt'] != 0 && 
				count($buildings) > 0 &&
				$wcnt < $vmaxwater &&
				$totalwcount >= ($vmaxwater - $wcnt)
				) {
				$vItem['watercnt']=$vmaxwater - $wcnt;
				$vTDB[]=$vItem;
				unset($vItem['watercnt']);
				unset($buildings[$vItem]);
				$totalwcount = $totalwcount - ($vmaxwater - $wcnt);
				if ($vSettings['Seedunkcnt']>0) $vSettings['Seedunkcnt']--;
			}
		}
	}
	if (count($vTDB)>0) {
		AFT_save($vSettings, 'settings');
		AFT_save($vAllTrees, 'alltrees');
		AddLog2('AllForTrees -> Watering '.count($vTDB).' Mystery Seedlings...');
		AddLog('AllForTrees -> Watering '.count($vTDB).' Mystery Seedlings...');
		AFT_AMFwater($vTDB);
	}
}
function AllForTrees_GBTreeSell() {
	AddLog2("AllForTrees [Giftbox selling]");

	$vSettings = AFT_load('settings');
	
	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	

	foreach ($vAllTrees as $vItem) {
		if ($vItem['cntGB'] > 0  && 
				($vSettings['GBSellMastered'] && $vItem['mastery'] >= 1
					&& $vItem['coins'] < $vSettings['preciousCoins']
					&& $vItem['cocos'] < $vSettings['preciousCocos']
					&& $vItem['jade'] < $vSettings['preciousJade']
				)
			) {
			AddLog2("AllForTrees -> Selling all {$vItem['cntGB']} mastered {$vItem['realname']} from giftbox.");
			AMF_SellItemInObject($vItem['code'], $vItem['cntGB'], -1);
			$need_reload = true;
		}

		if ($vItem['cntGB'] > 0  && (
				$vItem['actionGB'] == 'sell'  && ($vItem['cntGB'] - $vItem['actionGBcnt'] >= 0 )
			)
			) {
			AddLog2('AllForTrees -> Selling '.($vItem['cntGB'] - $vItem['actionGBcnt'])." {$vItem['realname']} from giftbox.");
			AMF_SellItemInObject($vItem['code'], $vItem['cntGB'] - $vItem['actionGBcnt'], -1);
			$need_reload = true;
		}
	}
}
function AllForTrees_StorageTreeSell() {
	AddLog2("AllForTrees [Storage selling]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	global $vWorldtype;
	switch ($vWorldtype) {
		case 'farm':
			$iTarget = -2;
			break;
		case 'england':
			$iTarget = -8;
			break;
		case 'fisherman':
			$iTarget = -9;
			break;
		case 'winterwonderland':
			$iTarget = -10;
			break;
		case 'hawaii':
			$iTarget = -11;
			break;
	}

	foreach ($vAllTrees as $vItem) {
		if (($vItem['actionST'] == 'sell') && 
		($vItem['cntST'] > 0 ) && 
		($vItem['cntST'] - $vItem['actionSTcnt'] >= 0 )) {
			AddLog2('AllForTrees -> Selling '.$vItem['cntST'] - $vItem['actionSTcnt'].' '.$vItem['realname'].' from Storage.');
			AMF_SellItemInObject($vItem['code'], $vItem['cntST'] - $vItem['actionSTcnt'], $iTarget);
			$need_reload = true;
		}
	}
}
function AllForTrees_GBTreePlace() {
	AddLog2("AllForTrees [Giftbox placing]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	$vTDB=array();
	$vItem=array();	
	$num = 0;
	
	$settings = AFT_load('settings');
	
	foreach( $vAllTrees as $vTree) {
		if ($vTree['cntGB'] > 0  && (
				($settings['GBPlaceUnmastered'] && $vTree['mastery'] < 1)
				|| ($vTree['actionGB'] == 'place'  && ($vTree['cntGB'] - $vTree['actionGBcnt'] >= 0 ))
				)
			) {

			for ($i=0; $i< $vTree['cntGB'] - $vTree['actionGBcnt'] ;$i++) {
				$vLocation = AllForTrees_GetFreeLocation($num);
				$num++;
				$vItem['itemName']=$vTree['name'];
				$vItem['position']['x']=$vLocation['x'];
				$vItem['position']['y']=$vLocation['y'];
				$vItem['state']='static';
				$vItem['isGift']='true';
				$vItem['className']='Tree';
				$vItem['strid']=-1;
				$vTDB[]=$vItem;				
			}
		}
	}
	if (count($vTDB)>0) {
		AddLog2('AllForTrees -> placing '.count($vTDB).' trees from giftbox...');
		AFT_AMFSTRtoFarm($vTDB);
	}	
}
function AllForTrees_StorageTreePlace() {
	AddLog2("AllForTrees [Storage placing]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	global $vWorldtype;
	switch ($vWorldtype) {
		case 'farm':
			$iTarget = -2;
			break;
		case 'england':
			$iTarget = -8;
			break;
		case 'fisherman':
			$iTarget = -9;
			break;
		case 'winterwonderland':
			$iTarget = -10;
			break;
		case 'hawaii':
			$iTarget = -11;
			break;
	}
	
	$vTDB=array();
	$vItem=array();	
	$num = 0;
	foreach( $vAllTrees as $vTree) {
		if (($vTree['actionST'] == 'place') &&  ($vTree['cntST'] > 0 ) && ($vTree['cntST'] - $vTree['actionSTcnt'] >= 0 )) {
			for ($i=0; $i< $vTree['cntST'] - $vTree['actionSTcnt'] ;$i++) {
				unset($vItem);
				$vLocation = AllForTrees_GetFreeLocation($num);
				$num++;
				$vItem['itemName']=$vTree['name'];
				$vItem['position']['x']=$vLocation['x'];
				$vItem['position']['y']=$vLocation['y'];
				$vItem['state']='bare';
				$vItem['isGift']=false;
				$vItem['className']='Tree';
				$vItem['strid']=$iTarget;
				$vTDB[]=$vItem;				
			}
		}
	}
	if (count($vTDB)>0) {
		AddLog2('AllForTrees -> placing '.count($vTDB).' trees from storage...');
		AFT_AMFSTRtoFarm($vTDB);
	}	
}
function AllForTrees_Remove() {  // place trees from Orchards
	AddLog2("AllForTrees [Orchard placing]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	}	
#	$tdb = AFT_TreeIndex($vAllTrees);
	$objects  = @unserialize(file_get_contents(F('objects.txt')));
	$vOrchards = AFT_load('orchards');
	$settings = AFT_load('settings');
	$vTDB=array();
	$vItem=array();	
	$num = 0;

	foreach ($objects as $o) {
		$orcs[$o['id']]=$o;
	}
	$i = 0;

	for ($i = 0; $i < count($vOrchards['cnt']); $i++) {
		$cnt = $vOrchards['cnt'][$i];
		
		$o=$orcs[$vOrchards['oid'][$i]];
		if ($o['className']=='OrchardFeatureBuilding' || $o['className']=='OrchardBuilding' || $o['className'] == "ArboretumBuilding") {
			$vtemplist = array();
			foreach ($o['contents'] as $conts) {
				if ($vOrchards['tid'][$i]!=$conts['itemCode']) continue;
				$t = $vAllTrees[$conts['itemCode']];
				if ($conts['numItem'] < $vOrchards['cnt'][$i]) $vOrchards['cnt'][$i] = $conts['numItem'];
				if (! $t['name'] && $settings['removeIllegalItems']) { // if this is not a valid tree
					$vItem = Units_GetUnitByCode($conts['itemCode']);
					
					AddLog2("AllForTrees -> Found illegal object {$vItem['name']} in {$o['className']} {$o['id']}! Removing it.");
					$vOrchards['cnt'][$i]=$conts['numItem'];
					$cnt = $vOrchards['cnt'][$i];
#						$vtemplist[] = $vItem;
					continue;
				}
// Mithelen - Remove all Mastered					
				if ($t['mastery'] >= 1 && $settings['removeAllMastered']) {
					AddLog2("AllForTrees -> Found ".$conts['numItem']." MASTERED {$t['realname']}(s) in {$o['className']}, removing them...");
					$vOrchards['cnt'][$i]=$conts['numItem'];
					$cnt = $vOrchards['cnt'][$i];
				}
// Mithelen
				if ($t['realname'] && $vOrchards['tid'][$i]==$conts['itemCode']) {
					if ($settings['removeUnmasteredFromOrchards']) {
						if ($t['mastery'] < 1) {
							AddLog2("AllForTrees -> Found ".$conts['numItem']." un-mastered {$t['realname']}(s) in {$o['className']}, removing them...");
							$vOrchards['cnt'][$i]=$conts['numItem'];
							$cnt = $vOrchards['cnt'][$i];
						} elseif ($t['actionBred'] == "spare" || $t['actionBred'] == "forced" || $t['actionBred'] == "tocnt") {
							AddLog2("AllForTrees -> Found ".$conts['numItem']." {$t['actionBred']} {$t['realname']}(s) in {$o['className']}, removing them...");
							$vOrchards['cnt'][$i]=$conts['numItem'];
							$cnt = $vOrchards['cnt'][$i];
						}
					}
					$vrcnt=$vOrchards['cnt'][$i]; 
					if ($vrcnt<$cnt) { 
						$cnt=$vrcnt;
						$vOrchards['cnt'][$i]=$cnt;
					}
				}
			}
			// if ($vtemplist) {
				// AllForTrees_Amftransfertofarm($vtemplist, $o);
			// }
		}
		
		if ($cnt > 0) {
			for ($j = 0; $j < $cnt; $j++) {
				unset($vItem);
				
				$item = Units_GetUnitByCode($vOrchards['tid'][$i]);
				if (! Units_IsPlaceableByCode($vOrchards['tid'][$i])) {
					AddLog2("AllForTrees -> Item {$item['name']} in {$o{'className'}} #{$o{'id'}} is not placable");
					continue;
				}
				// $vLocation = AllForTrees_GetFreeLocation($num);
				// $num++;

		
				$vLocation = Parser_Find_Location($vOrchards['tid'][$i]);
				if (! $vLocation) continue;

				Parser_Occupy_Location($vLocation, $vOrchards['tid'][$i]);
			
				$vItem['itemName']=$item['name'];
				$vItem['position']['x']=$vLocation['x'];
				$vItem['position']['y']=$vLocation['y'];
				$vItem['state']='bare';
				$vItem['isGift']=false;
				$vItem['className']=$item['className'];;
				$vItem['strid']=$vOrchards['oid'][$i];
				$vTDB[]=$vItem;							
				$vOrchards['cnt'][$i]--;
			}
		}
	}
	
	AFT_save($vOrchards, 'orchards');
	if (count($vTDB)>0) {
		AddLog2('AllForTrees -> placing '.count($vTDB).' tree(s) from orchards...');
		AFT_AMFSTRtoFarm($vTDB);
	}		
}
function AllForTrees_Sell() {
	AddLog2("AllForTrees [Selling]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	$vTDB=array();
	$objects   = @unserialize(file_get_contents(F('objects.txt')));

	foreach ($vAllTrees as $vTree) {
		if ($vTree['action']=='sell') {
			$cntitm = $vTree['cnt'] - $vTree['actioncnt'];
			if ($cntitm > 0) {
				foreach ($objects as $oID => $o) {
					if ($o['itemName'] == $vTree['name'] && $cntitm > 0) {
						$vTDB[]=$o;
						$cntitm = $cntitm - 1;
					}
				}
			}
		}
	}

	if (count($vTDB)>0) {
		AddLog2('AllForTrees -> selling '.count($vTDB).' trees from the farm...');
		AFT_AMFsell($vTDB);
	}	
}
function AllForTrees_ToOrch() {
	AddLog2("AllForTrees [Orchard storing]");

	global $vAllTrees;
	global $vSettings;
	$vSettings        = AFT_load('settings');

	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	$vTDB=array();
	$vitem=array();
	$tcnt = array();
	global $vFobjects;
	$objects          = @unserialize(file_get_contents(F('objects.txt')));
	foreach ($objects as $oID => $o) {
		if ($o['className'] == 'Tree') $vFobjects[]=$o; 
	}
	$OrchardBuildings = array_merge(GetObjects('OrchardFeatureBuilding'), GetObjects('OrchardBuilding'), GetObjects('ArboretumBuilding'));
	AddLog2("AllForTrees -> ".count($vFobjects)." Trees and ".count($OrchardBuildings)." Orchards on farm");
	foreach ($OrchardBuildings as &$orchard) {
		$capacity = AFT_capa($orchard);

		$type = "";
		if (stristr($orchard['itemName'],"superorchard")) $type = "Super";
		if (stristr($orchard['className'],"ArboretumBuilding")) $type = "Grove";
		
		$treesInOrchard = AllForTrees_TreesInBuilding($orchard);
	
		$number = $capacity - $treesInOrchard -1;

		if ($treesInOrchard == 0 && $vSettings['populateOrchards']) {
			AddLog2("AllForTrees -> Populating {$orchard['itemName']} #{$orchard['id']} ...");
			
			
			if ($vSettings["populate{$type}With"]) {
				if ($vSettings["populate{$type}With"] == "anyMastered") {
					$vitem = array();
					foreach ($vAllTrees as &$t) {
						if ($t['mastery'] < 1) continue;
						if (! $t['cnt'] > 0) continue;
						$number--;
						$t['cnt']--;
						$vitem['name']=$t['name'];
						$vitem['realname']=$t['realname'];
						$vitem['code']=$t['code'];
						$oid= AllForTrees_GetUnitbyNum($t['name'], ++$tcnt[$t['code']]);
						$vitem['id']=$oid['id'];
						$vitem['orchard'] =$orchard;
						$vTDB[]=$vitem;
						break;
					}
					
				} elseif ($vSettings["populate{$type}With"] == "lowestMastery") {
					$mmc = -1;
					$t2 = null;
					foreach ($vAllTrees as &$t) {
						if ($t['mastery'] >= 1)
						{
//							AddLog2("Skipping Mastered:".$t['name']);
							continue;
						}
						if (! $t['cnt'] >= 1)
						{
//							AddLog2("Skipping Count = 0:".$t['name']);
							continue;
						}
						if ($mmc == -1) $mmc=$t['mascnt'];
						if ($t['mascnt']<=$mmc) {
							$mmc = $t['mascnt'];
							$t2 = $t;
						}
					}
					
					if (!$t2)
					{
						$number=0;
						continue;
					}
					
					$number--;
					$t2['cnt']--;
					$vitem['name']=$t2['name'];
					$vitem['realname']=$t2['realname'];
					$vitem['code']=$t2['code'];
					$oid= AllForTrees_GetUnitbyNum($t2['name'], ++$tcnt[$t2['code']]);
					$vitem['id']=$oid['id'];
					$vitem['orchard'] =$orchard;
					$vTDB[]=$vitem;
					$vAllTrees[$t2['code']]['cnt']--;
					AddLog2("AllForTrees -> Populating {$orchard['itemName']} #{$orchard['id']} with ".$vitem['realname']);
				} elseif ($vSettings["populate{$type}With"] == "highestMastery") {
					$mmc = 0;
					$t2;
					foreach ($vAllTrees as &$t) {
						if (! $t['mastery'] >= 1) continue;
						if (! $t['cnt'] >= 1) continue;
						if ($t['mascnt']>$mmc) {
							$mmc = $t['mascnt'];
							$t2 = $t;
						}
					}
					$number--;
					$t2['cnt']--;
					$vitem['name']=$t2['name'];
					$vitem['realname']=$t2['realname'];
					$vitem['code']=$t2['code'];
					$oid= AllForTrees_GetUnitbyNum($t2['name'], ++$tcnt[$t2['code']]);
					$vitem['id']=$oid['id'];
					$vitem['orchard'] =$orchard;
					$vTDB[]=$vitem;
					$vAllTrees[$t2['code']]['cnt']--;
					AddLog2("AllForTrees -> Populating {$orchard['itemName']} #{$orchard['id']} with ".$vitem['realname']);
				} elseif (preg_match('/^tree-/',$vSettings["populate{$type}With"])) {
					$tc = substr($vSettings["populate{$type}With"],5);
					$t = $vAllTrees[$tc];
					if ($t['cnt']>0) {
						$t['cnt']--;
						$vitem['name']=$t['name'];
						$vitem['realname']=$t['realname'];
						$vitem['code']=$t['code'];
						$oid= AllForTrees_GetUnitbyNum($t['name'], ++$tcnt[$t['code']]);
						$vitem['id']=$oid['id'];
						$vitem['orchard'] =$orchard;
						$vTDB[]=$vitem;
						AddLog2("AllForTrees -> Populating {$orchard['itemName']} #{$orchard['id']} with ".$vitem['realname']);
					} else {
						AddLog2("AllForTrees -> No more {$t['realname']} left to populate!");
					}
					
				}
			} else {
				AddLog2("AllForTrees -> No tree type set for orchard population!");
				$number = 0;
			}
		}
		
		
		foreach ($vAllTrees as $vTree) {
			$vatrcnt = $vTree['cnt'];
			while ($vTree['movetoorc']==$orchard['id'] && $number>0 && $vatrcnt>0) {
				$number--;
				$vatrcnt--;
				$vitem['name']=$vTree['name'];
				$vitem['realname']=$vTree['realname'];
				$vitem['code']=$vTree['code'];
				$oid= AllForTrees_GetUnitbyNum($vTree['name'], ++$tcnt[$vTree['code']]);
				$vitem['id']=$oid['id'];
				$vitem['orchard'] =$orchard;
				$vTDB[]=$vitem;
			}
		}
	}
		
	if (count($vTDB)>0) {
		AddLog2('AllForTrees -> moving '.count($vTDB).' trees to orchards...');
		AFT_AMFFarmtoStr($vTDB);
	}			
}
function AllForTrees_Move() {
	AddLog2("AllForTrees [Moving]");

	
	
#- Parser_Find_Location($vCode, $vHV='horizontal', $vSection='')
#- Parser_IsFree_Location($vLocation, $vCode, $vHV='horizontal')
#- Parser_Occupy_Location($vLocation, $vCode, $vHV='horizontal')
#- Parser_Free_Location($vLocation, $vCode, $vHV='horizontal')

	
	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	} //$need_reload == true	
	global $vAnnounceMoveArray;
	$objects   = @unserialize(file_get_contents(F('objects.txt')));
	$vSections = AFT_load('sections');
	foreach ($vSections as $s) {
		$Sections[$s['id']] = $s;
	}
	$vSettings = AFT_load('settings');
	$location_empty = array();
	
	
#	for ($x = 0; $x < $sizeX; $x++) {
#		for ($y = 0; $y < $sizeY; $y++) {
#			$location_empty[$x][$y] = true;
#		}
#	}

	// foreach ($objects as $o) {
		// $u = Units_GetUnitByName($o['itemName']);
		// if (!isset($u['sizeX'])) {
			// $u['sizeX'] = 1;
			// $u['sizeY'] = 1;
		// }
		// if ($o['state'] == 'vertical') {
			// $t          = $u['sizeX'];
			// $u['sizeX'] = $u['sizeY'];
			// $u['sizeY'] = $t;
		// }
		// for ($x = 0; $x < $u['sizeX']; $x++) {
			// for ($y = 0; $y < $u['sizeY']; $y++) {
				// $location_empty[$o['position']['x'] + $x][$o['position']['y'] + $y] = false;
			// }
		// }
	// }

	foreach ($vAllTrees as &$t) {
		if ($t['movetosec']) continue;
		if ($t['mastery'] < 1 && $vSettings['unmasteredSection']) {
			$t['movetosec'] = $vSettings['unmasteredSection'];
		} elseif ($vSettings['masteredSection']) {
			$t['movetosec'] = $vSettings['masteredSection'];
		}
	}
	
	$trees = GetObjects('Tree');
	// $tr=array();
	// foreach ($trees as $o) {
		// $tr[]=$o['itemName'];
	// }
	// array_multisort($tr, SORT_ASC, $trees); 
	
	foreach ($trees as $o) {
		$u = Units_GetUnitByName($o['itemName']);
		if (! $vAllTrees[$u{'code'}]['movetosec']) continue;

		$secID = $vAllTrees[$u{'code'}]['movetosec'];
		$sec = $Sections[$secID];
		
		if (AFT_inSec($u['code'],$o['position'],$sec)) continue;

		// AddLog2("Tree {$u{'code'}} [{$o['position']['x']}/{$o['position']['y']}] {$o{'itemName'}} --- section  {$vAllTrees[$u{'code'}]['movetosec']} ({$sec['name']}) ");
		
		$psec = array(
			'bot_x' => $sec['x1'],
			'bot_y' => $sec['y1'],
			'top_x' => $sec['x2'],
			'top_y' => $sec['y2'],
		);
		
		if ($newpos = Parser_Find_Location($u['code'],'horizontal',$psec)) {
			AddLog2("AllForTrees -> Moving {$o['itemName']} from {$o['position']['x']}/{$o['position']['y']} into section {$sec['id']} ({$sec['name']}) at {$newpos['x']}/{$newpos['y']}");
			Parser_Occupy_location($newpos,$u['code']);
			Parser_Free_location($o['position'],$u['code']);
			AllForTrees_Announce_Move($o, $newpos);
		}
	}
	if (count($vAnnounceMoveArray)) {
		AddLog2("AllForTrees -> Moving ".(count($vAnnounceMoveArray))." trees...");
		$result      = AllForTrees_AMFMove();
		$need_reload = $need_reload || $result;
	}
}
function AFT_inSec($code,$pos,$sec) {
	$vUnit = Units_GetUnitByCode($vCode);

    if($vUnit['sizeX']=='') $vUnit['sizeX']=1;
    if($vUnit['sizeY']=='') $vUnit['sizeY']=1;
	
	// AddLog2("{$code}: pos: {$pos['x']}/{$pos['y']} sec: {$sec['x1']}/{$sec['x2']}/{$sec['y1']}/{$sec['y2']} size: {$vUnit['sizeX']}/{$vUnit['sizeY']}");
	
	$vUnit['sizeX'] -= 1;
	$vUnit['sizeY'] -= 1;
	
	if ($pos['x']+$vUnit['sizeX'] > $sec['x2']
		|| $pos['x'] < $sec['x1']
		|| $pos['y']+$vUnit['sizeY'] > $sec['y2']
		|| $pos['y'] < $sec['y1']
		) return false;
	return true;
}
function AllForTrees_Find_Free_Location($sections, $unit, $o, $locs) {
	foreach ($sections as $sctn) {
		if ($sctn['order'] == '0y') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($x = $sctn['x1']; $x <= ($sctn['x2'] - $unit['sizeX'] + 1); $x++) {
					for ($y = $sctn['y1']; $y <= ($sctn['y2'] - $unit['sizeY'] + 1); $y++) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == '0x') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($y = $sctn['y1']; $y <= ($sctn['y2'] - $unit['sizeY'] + 1); $y++) {
					for ($x = $sctn['x1']; $x <= ($sctn['x2'] - $unit['sizeX'] + 1); $x++) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'y0') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($x = $sctn['x1']; $x <= ($sctn['x2'] - $unit['sizeX'] + 1); $x++) {
					for ($y = $sctn['y2']; $y >= ($sctn['y1'] - $unit['sizeY'] + 1); $y--) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'x0') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($y = $sctn['y1']; $y <= ($sctn['y2'] - $unit['sizeY'] + 1); $y++) {
					for ($x = $sctn['x2']; $x >= ($sctn['x1'] - $unit['sizeX'] + 1); $x--) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'r0y') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($x = $sctn['x2']; $x >= ($sctn['x1'] - $unit['sizeX'] + 1); $x--) {
					for ($y = $sctn['y1']; $y <= ($sctn['y2'] - $unit['sizeY'] + 1); $y++) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'r0x') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($y = $sctn['y2']; $y >= ($sctn['y1'] - $unit['sizeY'] + 1); $y--) {
					for ($x = $sctn['x1']; $x <= ($sctn['x2'] - $unit['sizeX'] + 1); $x++) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'ry0') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($x = $sctn['x2']; $x >= ($sctn['x1'] - $unit['sizeX'] + 1); $x--) {
					for ($y = $sctn['y2']; $y >= ($sctn['y1'] - $unit['sizeY'] + 1); $y--) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} elseif ($sctn['order'] == 'rx0') {
			if (in_array($o['itemName'], $sctn['content'])) {
				for ($y = $sctn['y2']; $y >= ($sctn['y1'] - $unit['sizeY'] + 1); $y--) {
					for ($x = $sctn['x2']; $x >= ($sctn['x1'] - $unit['sizeX'] + 1); $x--) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							return array(
								"x" => $x,
								"y" => $y
							);
					}
				}
			}
		} else {
			if (in_array($o['itemName'], $sctn['content'])) {
				$vfreelist = array();
				for ($x = $sctn['x1']; $x <= ($sctn['x2'] - $unit['sizeX'] + 1); $x++) {
					for ($y = $sctn['y1']; $y <= ($sctn['y2'] - $unit['sizeY'] + 1); $y++) {
						$is_available = true;
						for ($x2 = 0; $x2 < $unit['sizeX']; $x2++)
							for ($y2 = 0; $y2 < $unit['sizeY']; $y2++)
								if ($locs[$x + $x2][$y + $y2] == false)
									$is_available = false;
						if ($is_available)
							$vfreelist[] = array(
								"x" => $x,
								"y" => $y
							);
					}
				}
				if (count($vfreelist) > 0) {
					shuffle($vfreelist);
					return array(
						"x" => $vfreelist[0]['x'],
						"y" => $vfreelist[0]['y']
					);
				}
			}
		}
	}
	return false;
}
function AllForTrees_Announce_Move($target, $newpos) {
	global $vAnnounceMoveArray;
	$vAnnounceMoveArray[] = array(
		'target' => $target,
		'newpos' => $newpos
	);
}
function AllForTrees_AMFMove() {
	global $vAnnounceMoveArray;
	$px_Setopts = LoadSavedSettings();
	if ((!@$px_Setopts['bot_speed']) || (@$px_Setopts['bot_speed'] > 50) || (@$px_Setopts['bot_speed'] < 1)) {
		$vSpeed = 1;
	} else {
		$vSpeed = $px_Setopts['bot_speed'];
	}
	$vCntMoves    = count($vAnnounceMoveArray);
	$vRunMainLoop = ceil($vCntMoves / $vSpeed);
	for ($vI = 0; $vI < $vRunMainLoop; $vI++) {
		$need_reload                   = false;
		$res                           = 0;
		$amf                           = new AMFObject("");
		$amf->_bodys[0]                = new MessageBody();
		$amf->_bodys[0]->targetURI     = 'FlashService.dispatchBatch';
		$amf->_bodys[0]->responseURI   = '/1/onStatus';
		$amf->_bodys[0]->responseIndex = '/1';
		$amf->_bodys[0]->_value[0]     = GetAMFHeaders();
		unset($vMSG);
		$vNumAction = 0;
		for ($vJ = ($vI * $vSpeed); (($vJ < (($vI * $vSpeed) + $vSpeed)) && ($vJ < $vCntMoves)); $vJ++) {
			$target                                              = $vAnnounceMoveArray[$vJ]['target'];
			$newpos                                              = $vAnnounceMoveArray[$vJ]['newpos'];
			$amf->_bodys[0]->_value[1][$vNumAction]['params']    = array();
			$amf->_bodys[0]->_value[1][$vNumAction]['params'][0] = 'move';
			$amf->_bodys[0]->_value[1][$vNumAction]['params'][1] = $target;
			$amf->_bodys[0]->_value[1][$vNumAction]['params'][2] = array();
			if (isset($target['canWander']))
				$amf->_bodys[0]->_value[1][$vNumAction]['params'][2][0]['canWander'] = $target['canWander'];
			if (isset($target['state']))
				$amf->_bodys[0]->_value[1][$vNumAction]['params'][2][0]['state'] = $target['state'];
			if (isset($target['direction']))
				$amf->_bodys[0]->_value[1][$vNumAction]['params'][2][0]['direction'] = $target['direction'];
			$amf->_bodys[0]->_value[1][$vNumAction]['params'][2][0]['x'] = (int) $newpos['x'];
			$amf->_bodys[0]->_value[1][$vNumAction]['params'][2][0]['y'] = (int) $newpos['y'];
			$amf->_bodys[0]->_value[1][$vNumAction]['sequence']          = GetSequense();
			$amf->_bodys[0]->_value[1][$vNumAction]['sequenceID'] = $GLOBALS['sequence_id'];
			$amf->_bodys[0]->_value[1][$vNumAction]['functionName']      = 'WorldService.performAction';
			$vNumAction++;
			$vMSG[] = $newpos['x'] . '/' . $newpos['y'];
		}
		$amf->_bodys[0]->_value[2] = 0;
		AddLog2("AllForTrees -> Moving " . implode(' ', $vMSG));
		$res = RequestAMF($amf);
		AddLog2("AllForTrees -> result $res");
		if ($res === 'OK') $need_reload = true;
	}
	return ($need_reload);
}
function AllForTrees_GetGiftboxContent() {
	$ingiftbox = @unserialize(file_get_contents(F('ingiftbox.txt')));
	if (is_array($ingiftbox)) {
		foreach ($ingiftbox as $gift => $count) {
			list($qcount) = explode(',', $count);
			$vItem = Units_GetUnitByCode($gift);
			if ($vItem['type'] == 'animal') {
				$vItemTyp = 'animal';
			} elseif ($vItem['type'] == 'tree') {
				$vItemTyp = 'tree';
			} elseif ($vItem['type'] == 'decoration') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'rotateabledecoration') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'lootabledecoration') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'egg') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'mysterygift') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'flowerdecoration') {
				$vItemTyp = 'decoration';
			} elseif ($vItem['type'] == 'building') {
				$vItemTyp = 'building';
			} else {
				$vItemTyp = 'unused';
			}
			for ($vI = 0; $vI < $qcount; $vI++)
				$Return[$vItemTyp][] = $vItem;
		}
	}
	return $Return;
}
function AllForTrees__GetUnits() {
	$units = Units_GetByType('tree');
	foreach ($units as $unit) {
		$vTrees[$unit['name']] = $unit['name'];
	}
	ksort($vTrees);
	$vReturn['vTrees'] = $vTrees;
}
function AllForTrees__HowmanyinGB($vWhat) {
	$mscnt           = 0;
	$vGiftboxContent = AllForTrees_GetGiftboxContent();
	$building        = $vGiftboxContent['building'];
	foreach ($building as $bldng) {
		if ($bldng['name'] == $vWhat) {
			$mscnt = $mscnt + 1;
		}
	}
	return ($mscnt);
}
function AllForTrees_SQlite_Connect($vDBFile) {
	$vDB = new SQLiteDatabase($vDBFile);
	if (!$vDB) {
		AddLog2('AllForTrees -> Parser SQlite Error: cant open ' . $vDBFile);
		return (false);
	}
	$vDB->queryExec('PRAGMA cache_size=200000');
	$vDB->queryExec('PRAGMA synchronous=OFF');
	$vDB->queryExec('PRAGMA count_changes=OFF');
	$vDB->queryExec('PRAGMA journal_mode=MEMORY');
	$vDB->queryExec('PRAGMA temp_store=MEMORY');
	return $vDB;
}
function AllForTrees_GetStorageTreeData(){
	//$store_details     = array();
	$store_list        = @unserialize(file_get_contents(F('instorage.txt')));
	// $store_list_string = "";
	// foreach ($store_list as $storekey => $storenumItems) {
		// if ($storenumItems > 0) {
			// if ($store_list_string == "") {
				// $store_list_string = '"' . $storekey . '"';
			// } else {
				// $store_list_string = $store_list_string . ',"' . $storekey . '"';
			// }
		// }
	// }
	//print_r($store_list);
	/*
	Plugin Developer
223.09-parser got changed to sqlite3 (php_pdo_sqlite). if you query the $vDataDB you have to change you code to use parser-functions or you can change your code.

for getting one value from :
Code:	
    $vSQL='select content from units where name="cow" and field="realname"';
    $vResult = $vDataDB->query($vSQL);
    $vReturn=$vResult->fetchSingle();
    return($vReturn==''?$vName:$vReturn);	

to:
Code:	
    $vSQL='select content from units where name="cow" and field="realname"';
    list($vReturn)=PDO_Fetch_One($vDataDB,$vSQL);
    return($vReturn==''?$vName:$vReturn);	


for selecting rows from:
Code:	
    $vSQL='select name from units where field = "action" and content="harvest" and name in (select name from units where field="type" and content="animal") order by name';
    $vResult = @$vDataDB->query($vSQL);
    while ($vRow = @$vResult->fetch(SQLITE_ASSOC)) {
        $vReturn[]=$vRow['name'];
    }	

to:
Code:	
    $vSQL='select name from units where field = "action" and content="harvest" and name in (select name from units where field="type" and content="animal") order by name';
    foreach ($vDataDB->query($vSQL) as $vRow) {
        $vReturn[]=$vRow['name'];
    }	




in the 222.09-parser you have $vWorldtype as global, with 'farm', 'england', 'fisherman', 'winterwonderland' or 'hawaii'.
the F() and PluginF() functions prepend xuk, xlc, xww or xhi to the FBID, this way the 4 farms work like 4 differen accounts.
DoInit() creates the $vMap with locations free true/false
- Parser_Find_Location($vCode, $vHV='horizontal', $vSection='')
- Parser_IsFree_Location($vLocation, $vCode, $vHV='horizontal')
- Parser_Occupy_Location($vLocation, $vCode, $vHV='horizontal')
- Parser_Free_Location($vLocation, $vCode, $vHV='horizontal')
- AMF_SellItemInObject($vCode,$vAmount,$vObjectID) Sell Itemes out of Objects/Buildings (-1 for giftbox)
- AMF_AskForQuestItem($vQuest) Ask for items from running quest
- Parser_Place_From_Giftbox($vCode, $vLocation)

 */
	
/*	if ($store_list_string == "") {
		#$vDataDB = null;
		#$vDataDB = AllForTrees_SQlite_Connect('data.sqlite');
		global $vDataDB;
		#$vResult = @$vDataDB->query('SELECT * FROM units WHERE name IN (SELECT name FROM units WHERE field = "code" AND content IN (' . $store_list_string . ')) AND field IN ("code","name","type","masterymax","giftable","realname","iconurl","objectId","cost","sizeX","sizeY","className")');
		$vSQL = 'SELECT * FROM units WHERE name IN (SELECT name FROM units WHERE field = "code" AND content IN (' . $store_list_string . ')) AND field IN ("code","name","type","masterymax","giftable","realname","iconurl","objectId","cost","sizeX","sizeY","className")';
		#if ($vResult === false) {
			#return array();

		#}
		#while (@$vRow = $vResult->fetch(SQLITE_ASSOC)) {
			#$store_details[$vRow['name']][$vRow['field']] = $vRow['content'];
		#}
		
		foreach($vDataDB->query($vSQL) as $vRow) {
			$store_details[$vRow['name']][$vRow['field']] = $vRow['content'];
		}
	}
	
	*/
	
	$vTrees = Units_GetByType("tree", true);
	
	
	
	
	
	$item_list = array();
	
	foreach ($store_list as $code => $num) {
		$name = Units_GetNameByCode($code);
		$chkopt = $vTrees[$name];
					$tmp_item               = array();
					$tmp_item["code"]       = $chkopt["code"];
					$tmp_item["name"]       = $chkopt["name"];
					$tmp_item["realname"]   = $chkopt["realname"];
					$tmp_item["iconurl"]    = $chkopt["iconurl"];
					$tmp_item["masterymax"] = $chkopt["masterymax"];
					$tmp_item["treeamount"] = $num;
					$item_list[]            = $tmp_item;
		
	}
	
	
	// foreach ($store_details as $chkopt) {
		// $tmpstring = $chkopt["type"];
		// if ($tmpstring == 'tree') {
			// foreach ($store_list as $storekey => $storenumItems) {
				// if ($storekey == $chkopt["code"]) {
					// $tmp_item               = array();
					// $tmp_item["code"]       = $chkopt["code"];
					// $tmp_item["name"]       = $chkopt["name"];
					// $tmp_item["realname"]   = $chkopt["realname"];
					// $tmp_item["iconurl"]    = $chkopt["iconurl"];
					// $tmp_item["masterymax"] = $chkopt["masterymax"];
					// $tmp_item["treeamount"] = $storenumItems;
					// $item_list[]            = $tmp_item;
				// }
			// }
		// }
	// }
	return $item_list;
}
function AFT_tr($tree,$cols) {
	$line = "";
	foreach ($cols as $col) {
		$line .= "\t\t\t<td"
			.($col == "nameF"?' style="width:200px;"':'')
			.($col == "mastery"?" sorttable_customkey=\"{$tree['mastery']}\"":'')
			.">\n";
		$line .= AFT_td($tree,$col)."</td>\n";
	}
	return $line;
}
function AFT_OrcProgress($o) {
	global $vWorldTime;
	$dur = 46; // standard is 2 days (2x 23h)
	if ( stristr($o['itemName'],"superorchard")) $dur = 23; // super orchards ripen in 23 h
	$dur *= 60*60; // duration in seconds
	$plant = $o['plantTime']/1000; // planting time of orchard
	//if ($o['aoePlantTime']) $plant = $o['aoePlantTime']/1000;
	if ($plant < 1) return;
	
	$fin = $plant + $dur; // this is when the orchard will be finished
	$done = $vWorldTime-$plant;
	$progress = $done/$dur;
	$percent = intval(100 * $progress);
	$togo = intval(($fin-$vWorldTime) / 60); # minutes
	if ($togo > 120) {
		$togo = "ripe in ".intval($togo/60)." h";
	} elseif ($togo > 0) {
		$togo = "ripe in $togo min";
	} else {
		$togo = '';
	}
	$res = "{$percent}%<br>ripe: ".date("Y-m-d H:i:s",$fin)."<br>".$togo;
	
//	$res .= "worldtime = ".date("Y-m-d H:i:s",$vWorldTime);
//	$res .= "plant = ".date("Y-m-d H:i:s",$plant);
	return $res;
}
function AFT_td($tree,$type) {
	global $vSettings;
	if ($type == "icon") {
		return '<img width="60" height="60" src="'.str_replace("\\", "/", getcwd()).'/'.$tree['iconurl'].'"'
		." onclick=\"aftInfo('{$tree['name']}');return false;\" title=\"{$tree['name']} [{$tree['code']}]\">";
	} elseif ($type == "mastery") {
		$perc = floor($tree['mastery'] * 100);
		$pr = $perc;
		if ($pr > 100) $pr = 100;
		$left = $tree['masmax']-$tree['mascnt'];
		if ($left > 0) {
			$left = "<br>$left left";
		} else {
			$left = "";
		}
		$masimg = '<img src="file://' . AllForTreesBotpath . 'img/' . $tree['masstars'] . '_star.png">';
		
#		return "{$tree['mascnt']}/{$tree['masmax']} = {$perc}%";
		return "{$masimg}<br>{$tree['mascnt']}/{$tree['masmax']}$left<br>{$perc}%<br><div data-value=\"$pr\" class=\"masProgress\"></div>";
		
	} elseif ($type == "release") {
		return AFT_nowrap(date("Y-m-d", $tree['date']));
	} elseif ($type == "name" || $type=="nameF") {
		return AFT_nowrap($tree['realname']);
	} elseif ($type == "coins") {
		return $tree['coins']>$vSettings['preciousCoins']?"<b>{$tree['coins']}</b>":$tree['coins'];
	} elseif ($type == "cocos") {
		return $tree['cocos']>$vSettings['preciousCocos']?"<b>{$tree['cocos']}</b>":$tree['cocos'];
	} elseif ($type == "jade") {
		return $tree['jade']>$vSettings['preciousJade']?"<b>{$tree['jade']}</b>":$tree['jade'];
	} elseif ($type == "count") {
		return $tree['cnt'];
	} elseif ($type == "countOrchard") {
		return $tree['cntOrc'];
	} elseif ($type == "countSeed") {
		return $tree['cntSeed'];
	} elseif ($type == "countGB") {
		return $tree['cntGB'];
	} elseif ($type == "orcsNeeded") {
		$num = $tree['cnt'];
		if ($num > 19) $num = 19;
		$c = ceil(($tree['masmax']-$tree['mascnt'])/$num);
		if ($c <= 0) $c = "none";
		return $c;
	} elseif ($type == "action-GB") {
		return AFT_td_action($tree,"GB");
	}
}
function AFT_td_action($tree,$type) {
	$s = '<table class="blind"><tbody><tr>';
	$s .= '<td>Action</td>';
	$s .= "<td><select name=\"actn\" size=\"1\" onchange=\"fAction('faction=action$type&name={$tree['name']}&actn=',this.value)\">";

	if ($type == "GB") {
		$s .= '<option value=""' . ($tree["action$type"] == ''? ' selected':'' ). '>&nbsp;</option>';
		$s .= '<option value="sell"' . ($tree["action$type"] == 'sell'? ' selected':'' ). '>sell</option>';
		$s .= '<option value="place"' . ($tree["action$type"] == 'place'? ' selected':'' ). '>place</option>';
		$s .= '</select></td></tr>';
		$s .= '<tr><td>Keep</td>';
		$val = $tree["action{$type}cnt"];
		$s .= "<td><input name=\"keep\" size=\"3\" type=\"text\" value=\"{$val}\"  "
		."onchange=\"fAction('faction=action{$type}cnt&name={$tree['name']}&keep=',this.value)\">";
		$s .= "</td></tr>";
	}
	$s .= "</table>\n";
	return $s;
}
function AFT_nowrap($str) {
	return '<div style="white-space:nowrap;text-align:left;">'. $str . "</div>";
}
function AllForTrees_OProgress($type,$min,$max) {
	$object_list = load_botarray(F("objects.txt"));
	$numberorc = 0;
	$all = 0;
	global $vWorldTime;
	foreach($object_list as $orchard) {
		$orcClass = $orchard['className'];
		$orcState = $orchard['state'];
		if ($type == "O" && ($orcClass == 'OrchardFeatureBuilding'||$orcClass == 'OrchardBuilding') && !stristr($orchard['itemName'],"superorchard") ) {
			$all++;
			$done = $vWorldTime-($orchard['plantTime']/1000);
			$progress = $done/(46*60*60);
			if ($progress < $max && $progress >= $min) $numberorc++;
			if ($max==1 && $progress >= $max) $numberorc++;
			if ($min==0 && $progress <= $min) $numberorc++;
		} elseif ($type == "SO" && stristr($orchard['itemName'],"superorchard")) {
			$all++;
			$done = $vWorldTime-($orchard['plantTime']/1000);
			$progress = $done/(23*60*60);
			if ($progress < $max && $progress >= $min) $numberorc++;
			if ($max==1 && $progress >= $max) $numberorc++;
			if ($min==0 && $progress <= $min) $numberorc++;
		} elseif ($type == "G" && $orcClass == 'ArboretumBuilding') {
			$all++;
			$done = $vWorldTime-($orchard['plantTime']/1000);
			$progress = $done/(46*60*60);
			if ($progress < $max && $progress >= $min) $numberorc++;
			if ($max==1 && $progress >= $max) $numberorc++;
			if ($min==0 && $progress <= $min) $numberorc++;
		}
	}
	$part = ceil(100*$numberorc/$all);
	$gr = ceil(255 - ($part*2.55));
	return "<div style=\"position:relative;height:13px;\"><div style=\"z-index:0;position:absolute;background-color:#80ff80;width:{$part}%\">&nbsp;</div><div style=\"position:absolute;z-index:10;\">$numberorc ($part%)</div></div>";
}
function AllForTrees_Breeder() {

	$vSettings = AFT_load('settings');
	if (! $vSettings['Breeding_enabled']) {
		AddLog2("AllForTrees [Breeding] disabled");
		return;
	}

	AddLog2("AllForTrees [Breeding]");

	global $vAllTrees;
	global $need_reload;
	if ($need_reload == true) {
		$res         = DoInit();
		$vAllTrees = AFT_MakeTreeDB('all');			
		$need_reload = false;
	}

	if ($vSettings['breedingOrder']) {
		$vAllTrees=subval_sort($vAllTrees,$vSettings['breedingOrder']);
		if ($vSettings['breedingOrderDir'] == 'desc') $vAllTrees=array_reverse($vAllTrees);
	}

	global $vFobjects;

	$objects          = @unserialize(file_get_contents(F('objects.txt')));

	foreach ($objects as $oID => $o) {
		if ($o['className'] == 'Tree') $vFobjects[]=$o; 
	}
	
	$vtemplist         = array();
	$totalcount_ticker = 0;
	$totalcount        = AllForTrees_TotalOrchard();
	// $object_list       = load_botarray(F("objects.txt"));

	$numripe =0;
	foreach ($objects as $o) {
		if (($o['className'] == 'OrchardFeatureBuilding'
				|| $o['className'] == 'ArboretumBuilding'
				|| $o['className'] == 'OrchardBuilding'
				)
			&& $o['state'] == 'ripe') $ripeorcs[] = $o;
	}
	$numripe = count($ripeorcs);
	
	if ($numripe > 0) {
		AddLog2("AllForTrees -> [{$numripe}] ripe orchards/groves. Starting Breeding!");
	} else {
		AddLog2("AllForTrees -> No ripe orchards/groves.");
	}

	$breedStart = time();
	$last_reload = time();
	# TODO: sort orchards by capacity, breed big ones (=superorchards) first to maximize throughput
	
	$ripeorcs = array_reverse(subval_sort($ripeorcs,'expansionLevel'));
	
	foreach ($ripeorcs as $orchard) {
		$time = time();
		$orcID        = $orchard['id'];
		$orcClass     = $orchard['className'];
		$orcState     = $orchard['state'];
		$orcx         = $orchard['position']['x'];
		$orcy         = $orchard['position']['y'];
		$orcName      = $orchard['itemName'];
		$orcPlantTime = $orchard['plantTime'];
		unset($vtemplist);
		$vSettings = AFT_load('settings');

		$capacity = AFT_capa($orchard);

		if ($vSettings['maxHarvestPerCycle'] > 0 && $totalcount_ticker >= $vSettings['maxHarvestPerCycle']) {
			AddLog2("AllForTrees -> Stopped breeding after harvesting {$totalcount_ticker}. Continuing in next cycle.");
			break;
		}

		$bmin = (time()-$breedStart)/60;
		if ($vSettings['maxBreedTimePerCycle'] > 0 && $bmin >= $vSettings['maxBreedTimePerCycle']) {
			AddLog2("AllForTrees -> Stopped breeding after {$bmin} minutes. Continuing in next cycle.");
			break;
		}
		
		if ($vSettings['breedingResort'] && $vSettings['breedingOrder']) {
			AddLog2("AllForTrees -> resorting tree breeding list by {$vSettings['breedingOrder']} ({$vSettings['breedingOrderDir']})");
			$vAllTrees=subval_sort($vAllTrees,$vSettings['breedingOrder']);
			if ($vSettings['breedingOrderDir'] == 'desc') $vAllTrees=array_reverse($vAllTrees);
		}
		$number = $capacity - AllForTrees_TreesInBuilding($orchard);
		AddLog2("AllForTrees -> $orcClass #$orcID - Capacity: $capacity, available = $number");
		if ($number <= 0) {
			if ($vSettings['harvestorc'] == true) AllForTrees_harvest($orchard);
			++$totalcount_ticker;
			AddLog2("AllForTrees -> Harvested non-breeding orchard [$totalcount_ticker/$totalcount]");
			continue;
		}
		//forced trees
		foreach ($vAllTrees as $t) {
			$vatrcnt = $t['cnt'] < $t['actionBredcnt']?$t['cnt']:$t['actionBredcnt']; // use max. 'actionBredcnt' trees
			$tcnt=0;
			while ($t['actionBred'] == 'forced' && $number > 0 && $vatrcnt > 0) {
				$number--;
				$vatrcnt--;
				$tcnt++;
				$vtemplist[] = AllForTrees_GetUnitbyNum($t['name'], $tcnt);
			}
		}
		//tocount trees
		foreach ($vAllTrees as &$t) {
			$vatrcnt = $t['cnt'];
			$tcnt=0;
			while (
				$t['actionBred'] == 'tocnt' && 
				$t['actionBredcnt'] > 0 && 
				$number > 0 && 
				$vatrcnt > 0) {
					$number--;
					$vatrcnt--;
					$tcnt++;
					$t['actionBredcnt']--;
					$vtemplist[] = AllForTrees_GetUnitbyNum($t['name'], $tcnt);
			}
		}
		//tomastery trees
		foreach ($vAllTrees as &$t) {
			$vatrcnt = $t['cnt'];
			$tcnt=0;
			while (
				$t['actionBred'] == 'tomast' && 
				$t['masmax'] > $t['mascnt'] && 
				$number > 0 && 
				$vatrcnt > 0) {
					$number--;
					$vatrcnt--;
					$tcnt++;
					$t['mascnt']++;
					$vtemplist[] = AllForTrees_GetUnitbyNum($t['name'], $tcnt);
					#AddLog2("AllForTrees -> Breeding {$t['name']} (mastery={$t['mastery']})");
			}
		}
		
		//spare trees
		foreach ($vAllTrees as $t) {
			$vatrcnt = $t['cnt'] < $t['actionBredcnt']?$t['cnt']:$t['actionBredcnt']; // use max. 'actionBredcnt' trees
			$tcnt=0;
			while (
				$t['actionBred'] == 'spare' && 
				$number > 0 && 
				$vatrcnt > 0) {
					$number--;
					$vatrcnt--;
					$tcnt++;
					$vtemplist[] = AllForTrees_GetUnitbyNum($t['name'], $tcnt);
			}
		}
		
		++$totalcount_ticker;
		if (count($vtemplist) > 0) {
			AllForTrees_Amftransfertoorchard($vtemplist, $orchard);
			AllForTrees_harvest($orchard);
			
			// register mastery increase and calculate percentage
			foreach ($vtemplist as $tl) {
				$co = Units_GetCodeByName($tl['itemName']);
#				AddLog2("old mastery for $co ({$vAllTrees[$co]['realname']})={$vAllTrees[$co]['mascnt']}/{$vAllTrees[$co]['mastery']}");
#				$vAllTrees[$co]['mascnt']++;
				if ($vAllTrees[$co]['masmax']==0) {
					$vAllTrees[$co]['mastery']=0;
				} else {
					$vAllTrees[$co]['mastery']=round(($vAllTrees[$co]['mascnt'] / $vAllTrees[$co]['masmax']), 3);
				}
#				AddLog2("new mastery for $co ({$vAllTrees[$co]['realname']})={$vAllTrees[$co]['mascnt']}/{$vAllTrees[$co]['mastery']}");
			}
			
			$vtemplist = AllForTrees_Amftransfertofarm($vtemplist, $orchard);
			AllForTrees_SetUnitbyArr($vtemplist);
			$dur = time()-$time;
			AddLog2("AllForTrees -> Progress [$totalcount_ticker/$totalcount] in $dur seconds.");
		}
		
		if ($vSettings['doInitAfterMinBreeding'] > 0 && ((time()-$last_reload)/60) > $vSettings['doInitAfterMinBreeding']) {
			$res         = DoInit();
			$vAllTrees = AFT_MakeTreeDB('all');
			$last_reload=time();
		}
	}
}
function AllForTrees_Amftransfertoorchard($vtemplist, $orchard) {
	global $need_reload;
	$need_reload               = true;
	$vcnt                      = count($vtemplist);
	$Sspeed                    = 8;
	$i                         = 0;
	$amf                       = new AMFObject("");
	$amf->_bodys[0]            = new MessageBody();
	$amf->_bodys[0]->targetURI = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->_value[0] = GetAMFHeaders();
	$amf->_bodys[0]->_value[2] = 0;

	while ($i < $vcnt) {
		$sNumAction = 0;
		$resstr='';
		while ($sNumAction < $Sspeed && $i < $vcnt) {
			$amf->_bodys[0]->_value[1][$sNumAction]['sequence']                         = GetSequense();
			$amf->_bodys[0]->_value[1][$sNumAction]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$sNumAction]['functionName']                     = 'WorldService.performAction';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][0]                        = "store";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]                        = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id']                  = $orchard['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted']             = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId']              = -1;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state']               = $orchard['state'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName']            = $orchard['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']            = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x']       = $orchard['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y']       = $orchard['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z']       = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className']           = $orchard['className'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime']           = $orchard['plantTime'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['buildTime']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['components']          = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['contents']            = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2]                        = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]                     = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedClassName']  = "Tree";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemName']   = $vtemplist[$i]['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['metadata']         = "";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['storedItemCode']   = Units_GetCodeByName($vtemplist[$i]['itemName']);
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['resource']         = $vtemplist[$i]['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isFull']           = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['cameFromLocation'] = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isGift']           = false;
			$resstr=$resstr. ' '. $vtemplist[$i]['itemName'].',';
			$sNumAction++;
			$i++;
		}
		$res = RequestAMF($amf);
		AddLog2("AllForTrees -> moving to {$orchard['className']} #{$orchard['id']}, {$resstr}.  Result: $res ");

		unset($amf->_bodys[0]->_value[1]);
	}
}
function AllForTrees_Amftransfertofarm($vtemplist, $orchard) { // used by BREEDER and works!
	global $need_reload;
	$need_reload = true;
	$vcnt        = count($vtemplist);
	$j           = 0;
	global $vCnt63000;
	if ($vCnt63000 < 63000) $vCnt63000 = 63000;
	$Sspeed                        = 8;
	$amf                           = new AMFObject("");
	$amf->_bodys[0]                = new MessageBody();
	$amf->_bodys[0]->targetURI     = 'FlashService.dispatchBatch';
	$amf->_bodys[0]->responseURI   = '/1/onStatus';
	$amf->_bodys[0]->responseIndex = '/1';
	$amf->_bodys[0]->_value[0]     = GetAMFHeaders();
	$amf->_bodys[0]->_value[2]     = 0;

	while ($j < $vcnt) {
		$sNumAction = 0;
		$resstr='';
		while ($sNumAction < $Sspeed && $j < $vcnt) {
			$amf->_bodys[0]->_value[1][$sNumAction]['functionName']                        = "WorldService.performAction";
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][0]                           = 'place';
			$amf->_bodys[0]->_value[1][$sNumAction]['sequence']                            = GetSequense();
			$amf->_bodys[0]->_value[1][$sNumAction]['sequenceID'] = $GLOBALS['sequence_id'];

			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]                           = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['id']                     = $vCnt63000++;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['deleted']                = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['itemName']               = $vtemplist[$j]['itemName'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['tempId']                 = -1;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['direction']              = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['x']          = $vtemplist[$j]['position']['x'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['y']          = $vtemplist[$j]['position']['y'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['position']['z']          = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['plantTime']              = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['state']                  = 'bare';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][1]['className']              = 'Tree';
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2]                           = array();
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isGift']              = false;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['isStorageWithdrawal'] = $orchard['id'];
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energyCost']          = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energySource']        = 0;
			$amf->_bodys[0]->_value[1][$sNumAction]['params'][2][0]['energyMetadata']      = '';
			$resstr=$resstr. ' '. $vtemplist[$j]['itemName'].',';
			$sNumAction++;
			$j++;
		}
		$amf2 = RequestAMFIntern($amf);
		$vtemplist = AllForTrees_CheckAMF2ResponsePlace($amf2,$vtemplist,$j);

		AddLog2("AllForTrees -> moving to farm $resstr");
		unset($amf->_bodys[0]->_value[1]);
	}
	return $vtemplist;
}
function AllForTrees_TreesInBuilding($orchardUnit) {
	$num = 0;
	foreach ($orchardUnit['contents'] as $items) {
		$num += $items['numItem'];
	}
	return $num;
}
function AllForTrees_TotalOrchard() {
	$objects = @unserialize(file_get_contents(F('objects.txt')));
	$count   = 0;
	foreach ($objects as $orchard) {
		$orchardclass = $orchard['className'];
		$orchardstate = $orchard['state'];
		if (($orchardclass == 'OrchardFeatureBuilding' 
			|| $orchardclass == 'ArboretumBuilding'
			|| $orchardclass == 'OrchardBuilding') && $orchardstate == 'ripe') {
			$count++;
		}
	}
	return $count;
}
function AllForTrees_getItemInfo($item_code) {
	$item_details = array();
	global $vDataDB;
	#$vDataDB      = AllForTrees_SQlite_Connect('data.sqlite');
	$vSQL      = 'SELECT * FROM units WHERE name = "' . $item_code . '" AND field IN ("code","name","type","giftable","realname","objectId","cost","cash","sizeX","sizeY","className","iconurl","limit","market","type","limitedEnd","iphoneonly","multiplace")';
	#if ($vResult === false)
		#return array();
	#while (@$vRow = $vResult->fetch(SQLITE_ASSOC)) {
		#$item_details[$vRow['field']] = $vRow['content'];
	#}
	
	foreach($vDataDB->query($vSQL) as $vRow) {
		$item_details[$vRow['field']] = $vRow['content'];
	}
	return $item_details;
}
function AllForTrees_harvest($orchard) {
	global $need_reload;
	$need_reload  = true;
    $amf = CreateRequestAMF('harvest', 'WorldService.performAction');
    $amf->_bodys[0]->_value[1][0]['functionName'] = 'WorldService.performAction';
    $amf->_bodys[0]->_value[1][0]['params'][0] = "harvest";
    $amf->_bodys[0]->_value[1][0]['params'][1] = array();
    $amf->_bodys[0]->_value[1][0]['params'][1]['id'] = $orchard['id'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['deleted'] = false;
    $amf->_bodys[0]->_value[1][0]['params'][1]['tempId'] = "NaN";
    $amf->_bodys[0]->_value[1][0]['params'][1]['state'] = $orchard['state'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['itemName'] = $orchard['name'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['position'] = array();
    $amf->_bodys[0]->_value[1][0]['params'][1]['position']['x'] = $orchard['position']['x'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['position']['y'] = $orchard['position']['y'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['position']['z'] = 0;
    $amf->_bodys[0]->_value[1][0]['params'][1]['direction'] = $orchard['direction'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['className'] = $orchard['className'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['plantTime'] = $orchard['plantTime'];
    $amf->_bodys[0]->_value[1][0]['params'][1]['buildTime'] = 0;
    $amf->_bodys[0]->_value[1][0]['params'][1]['components'] = "";
    $amf->_bodys[0]->_value[1][0]['params'][1]['contents'] = "";

	$amf->_bodys[0]->_value[1][0]['params'][2]                      = array();
	$amf->_bodys[0]->_value[1][0]['params'][2][0]                   = array();
	$amf->_bodys[0]->_value[1][0]['params'][2][0]['energyCost']     = 0;
	$amf->_bodys[0]->_value[1][0]['params'][2][0]['extraParams']    = "";
	$amf->_bodys[0]->_value[1][0]['params'][2][0]['energySource']   = 0;
	$amf->_bodys[0]->_value[1][0]['params'][2][0]['neighbourId']    = 0;
	$amf->_bodys[0]->_value[1][0]['params'][2][0]['energyMetadata'] = "";
	$res                                                            = RequestAMF($amf);
	$name = $orchard['className'];
	if (stristr($orchard['itemName'],"superorchard")) $name = "SuperOrchard";
	AddLog2("AllForTrees -> harvesting {$name} ... Result: $res");
	AddLog("AllForTrees -> harvesting {$name}... Result: $res");
}
function AllForTrees_GetUnitbyNum($vName, $num) {
	global $vFobjects;
	$i = 1;
	foreach ($vFobjects as $oID => $o) {
		if ($o['className'] !== 'Tree') continue;
		if ($o['itemName'] == $vName) {
			if ($i == $num) return $o;
			$i++;
		}
	}
	return false;
}
function AllForTrees_SetUnitbyArr($vtemplist) {
	global $vFobjects;
	for ($i=0; $i<count($vFobjects); $i++) {
		foreach ($vtemplist as $vtmplst) {
			if ($vtmplst['position']['x']==$vFobjects[$i]['position']['x'] &&
				$vtmplst['position']['y']==$vFobjects[$i]['position']['y'] &&
				$vtmplst['itemName']==$vFobjects[$i]['itemName']) {
				$vFobjects[$i]['id']=$vtmplst['id'];
			}			
		}
	}
}
function AllForTrees_CheckAMF2ResponsePlace($amf2,$vtemplist,$j) {
	$sira=Floor(($j - 1) / 8);
	$cnt= $j - (8 * $sira);
	for ($i=0; $i < $cnt ; $i++) { 
		$t=$i + (8 * $sira);
		if (!isset($amf2->_bodys[0]->_value['data'][$i]['data']['id'])) RestartBot();
		$vtemplist[$t]['id']  = $amf2->_bodys[0]->_value['data'][$i]['data']['id'];
		//addlog2($vtemplist[$t]['id'] .' => '.$amf2->_bodys[0]->_value['data'][$i]['data']['id']);
	}
	return $vtemplist;
}
function AFT_save($array, $filename) {
    global $this_plugin;
	if ($filename == "alltrees") { // cleanup alltrees
		foreach ($array as $c => $a ){
			$new = array();
			foreach (array('action','actioncnt','actionSeed','actionSeedcnt','actionGB','actionGBcnt','actionST',
				'actionSTcnt','actionBred','actionBredcnt','movetosec','movetoorc') as $i) {
				if ($a[$i]) $new[$i] = $a[$i];
			}
			if ($new['action'] == 'select') unset($new['action']);
			if ($new['actionSeed'] == 'select') unset($new['actionSeed']);
			if ($new['actionGB'] == 'select') unset($new['actionGB']);
			if ($new['actionBred'] == 'tomast') unset($new['actionBred']);
			if (count($new)) $newarray[$c] = $new;
		}
		$array=$newarray;
	}
	$filename .= ".json";
    file_put_contents($this_plugin['folder'] . '/data/' . PluginF($filename),json_encode($array));
}
function AFT_load($filename) {
    global $this_plugin;
	$filenameT = $filename.".txt";
	$filenameJ = $filename.".json";
	if (! file_exists($this_plugin['folder'] . '/data/' . PluginF($filenameJ))) {
		$ar = array();
		$ar = load_array($filenameT);
		AFT_save($ar,$filename);
	}
    return @json_decode(file_get_contents($this_plugin['folder'] . '/data/' . PluginF($filenameJ)),true);
}
function AFT_capa($orchard) {
	$capacity = 10 + ($orchard['expansionLevel'] * 10);
	if ($capacity < 10) $capacity = 20;

	if ($orchard['className'] == "ArboretumBuilding") {
		$capacity = 20;
	}
	return $capacity;
}
function subval_sort($a,$subkey) {
	foreach($a as $k=>$v) {
		$b[$k] = strtolower($v[$subkey]);
	}
	asort($b);
	foreach($b as $key=>$val) {
		$c[$key] = $a[$key];
	}
	return $c;
}
?>